name
stringlengths
18
69
filepath
stringclasses
38 values
source
stringclasses
38 values
test
stringlengths
306
10.4k
AllGatherCombinerTest_CombineAllGathers
xla/service/all_gather_combiner_test.cc
int64_t FindMostFrequentGatherDim( absl::Span<HloInstruction* const> to_combine) { assert(!to_combine.empty()); // Count frequencies. int64_t min_rank = std::numeric_limits<int64_t>::max(); std::vector<int64_t> frequency; for (const HloInstruction* it : to_combine) { int64_t dim = Cast<HloAllGatherInstruction>(it)->all_gather_dimension(); frequency.resize(std::max(dim + 1, static_cast<int64_t>(frequency.size())), 0); frequency[dim]++; min_rank = std::min(min_rank, it->shape().rank()); } int64_t most_frequent_dim = std::distance( frequency.begin(), std::max_element(frequency.begin(), frequency.end())); return most_frequent_dim < min_rank ? most_frequent_dim : 0; } absl::Status CombineAllGathers(absl::Span<HloInstruction* const> to_combine, bool combine_by_dim) { if (to_combine.size() < 2) { return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; HloComputation& computation = *to_combine.back()->parent(); // Create a single bigger AllGather of the operands of the smaller AllGather. std::vector<HloInstruction*> operands; std::vector<std::optional<std::vector<int64_t>>> operand_permutations; std::vector<Shape> output_shapes; // Find the most frequent all-gather dimension. int64_t most_frequent_dim = FindMostFrequentGatherDim(to_combine); VLOG(1) << "Combining set"; for (HloInstruction* hlo : to_combine) { VLOG(1) << "Set element: " << hlo->ToString(); TF_RET_CHECK(hlo->opcode() == HloOpcode::kAllGather); const auto* ag = Cast<HloAllGatherInstruction>(hlo); TF_RET_CHECK(hlo->operand_count() == 1); TF_RET_CHECK(hlo->shape().IsArray()); TF_RET_CHECK(!combine_by_dim || ag->all_gather_dimension() == most_frequent_dim); HloInstruction* operand = hlo->operands().front(); operands.push_back(operand); operand_permutations.emplace_back(); output_shapes.push_back(hlo->shape()); // Bitcast operand if needed. if (ag->all_gather_dimension() != most_frequent_dim) { const Shape& operand_shape = operand->shape(); // Build permutation to align gather dimension. auto& perm = operand_permutations.back(); perm = std::vector<int64_t>(operand_shape.rank()); std::iota(perm->begin(), perm->end(), 0); std::swap((*perm)[most_frequent_dim], (*perm)[ag->all_gather_dimension()]); // Bitcast operand and update output shape. operands.back() = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*perm, operand_shape), operand)); output_shapes.back() = ShapeUtil::PermuteDimensions(*perm, hlo->shape()); } } // Create combined all-gather op with a tuple result. HloInstruction* combined; combined = computation.AddInstruction(HloInstruction::CreateAllGather( ShapeUtil::MakeTupleShape(output_shapes), operands, most_frequent_dim, to_combine.front()->device_list(), /*constrain_layout=*/false, to_combine.front()->channel_id(), Cast<HloAllGatherInstruction>(to_combine.front()) ->use_global_device_ids())); // We have to propagate the sharding manually because Domain instructions are // not guaranteed to preserve it for side effecting instructions. combined->set_sharding( hlo_sharding_util::CreateTupleSharding(combined->shape(), to_combine)); VLOG(1) << "Replacing with : " << combined->ToString(); // Replace all the smaller all-gather ops with (bitcast) elements of the tuple // result. for (int64_t i = 0; i < to_combine.size(); ++i) { HloInstruction* replacement = computation.AddInstruction( HloInstruction::CreateGetTupleElement(combined, i)); if (operand_permutations[i]) { replacement = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*operand_permutations[i], replacement->shape()), replacement)); } TF_RETURN_IF_ERROR( computation.ReplaceInstruction(to_combine[i], replacement)); } return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; VLOG(1) << "Combining set"; VLOG(1) << "Set element: " << hlo->ToString(); VLOG(1) << "Replacing with : " << combined->ToString(); std::optional<GroupKey> CombineKey(const HloInstruction* instruction, const HloDomainMap& domain_map, bool combine_by_dim) { if (instruction->opcode() != HloOpcode::kAllGather) { return std::nullopt; } std::vector<std::vector<int64_t>> replica_groups; const auto* ag = Cast<HloAllGatherInstruction>(instruction); replica_groups.reserve(ag->replica_groups().size()); for (const ReplicaGroup& replica_group : ag->replica_groups()) { replica_groups.push_back( std::vector<int64_t>(replica_group.replica_ids().begin(), replica_group.replica_ids().end())); } // Ignore dimension (set to -1) if we are not grouping by dimension. int64_t ag_dim_key = combine_by_dim ? ag->all_gather_dimension() : -1; return GroupKey{ag_dim_key, domain_map.GetDomainMetadataId(ag), ag->channel_id().has_value(), ag->use_global_device_ids(), replica_groups}; } AllGatherCombiner::AllGatherCombiner(int64_t combine_threshold_in_bytes, int64_t combine_threshold_count, bool combine_by_dim) : combine_threshold_in_bytes_(combine_threshold_in_bytes), combine_threshold_count_(combine_threshold_count), combine_by_dim_(combine_by_dim) {} absl::StatusOr<bool> AllGatherCombiner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { VLOG(1) << "Running AllGatherCombiner with threshold of " << combine_threshold_in_bytes_ << " bytes"; if (combine_threshold_in_bytes_ <= 0 || combine_threshold_count_ <= 0) { VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; return false; } if (hlo_query::ContainsLayoutConstrainedCollective(*module, HloOpcode::kAllGather)) { VLOG(1) << "Skip AllGatherCombiner because the module contains " "all-gather with constrained layouts"; return false; } bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, "")); auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); }; auto combine_fn = [&](absl::Span<HloInstruction* const> to_combine) -> absl::Status { return CombineAllGathers(to_combine, combine_by_dim_); }; TF_ASSIGN_OR_RETURN( bool computation_changed, CombineInstructionsByKey<GroupKey>(computation, key_fn, combine_fn, combine_threshold_in_bytes_, combine_threshold_count_)); changed |= computation_changed; } return changed; } VLOG(1) << "Running AllGatherCombiner with threshold of " VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; VLOG(1) << "Skip AllGatherCombiner because the module contains " auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); };
#include "xla/service/all_gather_combiner.h" #include <cstdint> #include <memory> #include <vector> #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" TEST_F(AllGatherCombinerTest, CombineAllGathers) { const char* const hlo_string = R"( HloModule Module ENTRY entry { param0 = f32[32] parameter(0) param1 = f32[32] parameter(1) allgather0 = f32[128] all-gather(param0), replica_groups={}, dimensions={0} allgather1 = f32[128] all-gather(param1), replica_groups={}, dimensions={0} ROOT tuple = (f32[128], f32[128]) tuple(allgather0, allgather1) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(hlo_string)); AllGatherCombiner combine(1024 * 1024, kMaxCombineCount, /*combine_by_dim=*/true); ASSERT_EQ(AllGatherCount(*module), 2); TF_ASSERT_OK_AND_ASSIGN(bool changed, combine.Run(module.get())); EXPECT_TRUE(changed); Matcher<const HloInstruction*> combined_all_gather = op::AllGather(op::Parameter(0), op::Parameter(1)); EXPECT_THAT(module->entry_computation()->root_instruction(), op::Tuple(op::GetTupleElement(combined_all_gather, 0), op::GetTupleElement(combined_all_gather, 1))); }
AllGatherCombinerTest_CombineAllGathersByAllGatherDimension
xla/service/all_gather_combiner_test.cc
int64_t FindMostFrequentGatherDim( absl::Span<HloInstruction* const> to_combine) { assert(!to_combine.empty()); // Count frequencies. int64_t min_rank = std::numeric_limits<int64_t>::max(); std::vector<int64_t> frequency; for (const HloInstruction* it : to_combine) { int64_t dim = Cast<HloAllGatherInstruction>(it)->all_gather_dimension(); frequency.resize(std::max(dim + 1, static_cast<int64_t>(frequency.size())), 0); frequency[dim]++; min_rank = std::min(min_rank, it->shape().rank()); } int64_t most_frequent_dim = std::distance( frequency.begin(), std::max_element(frequency.begin(), frequency.end())); return most_frequent_dim < min_rank ? most_frequent_dim : 0; } absl::Status CombineAllGathers(absl::Span<HloInstruction* const> to_combine, bool combine_by_dim) { if (to_combine.size() < 2) { return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; HloComputation& computation = *to_combine.back()->parent(); // Create a single bigger AllGather of the operands of the smaller AllGather. std::vector<HloInstruction*> operands; std::vector<std::optional<std::vector<int64_t>>> operand_permutations; std::vector<Shape> output_shapes; // Find the most frequent all-gather dimension. int64_t most_frequent_dim = FindMostFrequentGatherDim(to_combine); VLOG(1) << "Combining set"; for (HloInstruction* hlo : to_combine) { VLOG(1) << "Set element: " << hlo->ToString(); TF_RET_CHECK(hlo->opcode() == HloOpcode::kAllGather); const auto* ag = Cast<HloAllGatherInstruction>(hlo); TF_RET_CHECK(hlo->operand_count() == 1); TF_RET_CHECK(hlo->shape().IsArray()); TF_RET_CHECK(!combine_by_dim || ag->all_gather_dimension() == most_frequent_dim); HloInstruction* operand = hlo->operands().front(); operands.push_back(operand); operand_permutations.emplace_back(); output_shapes.push_back(hlo->shape()); // Bitcast operand if needed. if (ag->all_gather_dimension() != most_frequent_dim) { const Shape& operand_shape = operand->shape(); // Build permutation to align gather dimension. auto& perm = operand_permutations.back(); perm = std::vector<int64_t>(operand_shape.rank()); std::iota(perm->begin(), perm->end(), 0); std::swap((*perm)[most_frequent_dim], (*perm)[ag->all_gather_dimension()]); // Bitcast operand and update output shape. operands.back() = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*perm, operand_shape), operand)); output_shapes.back() = ShapeUtil::PermuteDimensions(*perm, hlo->shape()); } } // Create combined all-gather op with a tuple result. HloInstruction* combined; combined = computation.AddInstruction(HloInstruction::CreateAllGather( ShapeUtil::MakeTupleShape(output_shapes), operands, most_frequent_dim, to_combine.front()->device_list(), /*constrain_layout=*/false, to_combine.front()->channel_id(), Cast<HloAllGatherInstruction>(to_combine.front()) ->use_global_device_ids())); // We have to propagate the sharding manually because Domain instructions are // not guaranteed to preserve it for side effecting instructions. combined->set_sharding( hlo_sharding_util::CreateTupleSharding(combined->shape(), to_combine)); VLOG(1) << "Replacing with : " << combined->ToString(); // Replace all the smaller all-gather ops with (bitcast) elements of the tuple // result. for (int64_t i = 0; i < to_combine.size(); ++i) { HloInstruction* replacement = computation.AddInstruction( HloInstruction::CreateGetTupleElement(combined, i)); if (operand_permutations[i]) { replacement = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*operand_permutations[i], replacement->shape()), replacement)); } TF_RETURN_IF_ERROR( computation.ReplaceInstruction(to_combine[i], replacement)); } return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; VLOG(1) << "Combining set"; VLOG(1) << "Set element: " << hlo->ToString(); VLOG(1) << "Replacing with : " << combined->ToString(); std::optional<GroupKey> CombineKey(const HloInstruction* instruction, const HloDomainMap& domain_map, bool combine_by_dim) { if (instruction->opcode() != HloOpcode::kAllGather) { return std::nullopt; } std::vector<std::vector<int64_t>> replica_groups; const auto* ag = Cast<HloAllGatherInstruction>(instruction); replica_groups.reserve(ag->replica_groups().size()); for (const ReplicaGroup& replica_group : ag->replica_groups()) { replica_groups.push_back( std::vector<int64_t>(replica_group.replica_ids().begin(), replica_group.replica_ids().end())); } // Ignore dimension (set to -1) if we are not grouping by dimension. int64_t ag_dim_key = combine_by_dim ? ag->all_gather_dimension() : -1; return GroupKey{ag_dim_key, domain_map.GetDomainMetadataId(ag), ag->channel_id().has_value(), ag->use_global_device_ids(), replica_groups}; } AllGatherCombiner::AllGatherCombiner(int64_t combine_threshold_in_bytes, int64_t combine_threshold_count, bool combine_by_dim) : combine_threshold_in_bytes_(combine_threshold_in_bytes), combine_threshold_count_(combine_threshold_count), combine_by_dim_(combine_by_dim) {} absl::StatusOr<bool> AllGatherCombiner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { VLOG(1) << "Running AllGatherCombiner with threshold of " << combine_threshold_in_bytes_ << " bytes"; if (combine_threshold_in_bytes_ <= 0 || combine_threshold_count_ <= 0) { VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; return false; } if (hlo_query::ContainsLayoutConstrainedCollective(*module, HloOpcode::kAllGather)) { VLOG(1) << "Skip AllGatherCombiner because the module contains " "all-gather with constrained layouts"; return false; } bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, "")); auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); }; auto combine_fn = [&](absl::Span<HloInstruction* const> to_combine) -> absl::Status { return CombineAllGathers(to_combine, combine_by_dim_); }; TF_ASSIGN_OR_RETURN( bool computation_changed, CombineInstructionsByKey<GroupKey>(computation, key_fn, combine_fn, combine_threshold_in_bytes_, combine_threshold_count_)); changed |= computation_changed; } return changed; } VLOG(1) << "Running AllGatherCombiner with threshold of " VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; VLOG(1) << "Skip AllGatherCombiner because the module contains " auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); };
#include "xla/service/all_gather_combiner.h" #include <cstdint> #include <memory> #include <vector> #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" TEST_F(AllGatherCombinerTest, CombineAllGathersByAllGatherDimension) { const char* const hlo_string = R"( HloModule Module ENTRY entry { param0 = f32[2,2] parameter(0) param1 = f32[2,2] parameter(1) param2 = f32[2,2] parameter(2) param3 = f32[2,2] parameter(3) param4 = f32[2,2] parameter(4) allgather0 = f32[8,2] all-gather(param0), replica_groups={}, dimensions={0} allgather1 = f32[8,2] all-gather(param1), replica_groups={}, dimensions={0} allgather2 = f32[2,8] all-gather(param2), replica_groups={}, dimensions={1} allgather3 = f32[2,8] all-gather(param3), replica_groups={}, dimensions={1} allgather4 = f32[8,2] all-gather(param4), replica_groups={}, dimensions={0} ROOT tuple = (f32[8,2], f32[8,2], f32[2,8], f32[2,8], f32[8,2]) tuple(allgather0, allgather1, allgather2, allgather3, allgather4) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(hlo_string)); AllGatherCombiner combine(1024 * 1024, kMaxCombineCount, /*combine_by_dim=*/true); ASSERT_EQ(AllGatherCount(*module), 5); TF_ASSERT_OK_AND_ASSIGN(bool changed, combine.Run(module.get())); EXPECT_TRUE(changed); Matcher<const HloInstruction*> combined_all_gather0 = op::AllGather(op::Parameter(0), op::Parameter(1), op::Parameter(4)); Matcher<const HloInstruction*> combined_all_gather1 = op::AllGather(op::Parameter(2), op::Parameter(3)); EXPECT_THAT(module->entry_computation()->root_instruction(), op::Tuple(op::GetTupleElement(combined_all_gather0, 0), op::GetTupleElement(combined_all_gather0, 1), op::GetTupleElement(combined_all_gather1, 0), op::GetTupleElement(combined_all_gather1, 1), op::GetTupleElement(combined_all_gather0, 2))); }
AllGatherCombinerTest_CombineAllGathersByDim
xla/service/all_gather_combiner_test.cc
int64_t FindMostFrequentGatherDim( absl::Span<HloInstruction* const> to_combine) { assert(!to_combine.empty()); // Count frequencies. int64_t min_rank = std::numeric_limits<int64_t>::max(); std::vector<int64_t> frequency; for (const HloInstruction* it : to_combine) { int64_t dim = Cast<HloAllGatherInstruction>(it)->all_gather_dimension(); frequency.resize(std::max(dim + 1, static_cast<int64_t>(frequency.size())), 0); frequency[dim]++; min_rank = std::min(min_rank, it->shape().rank()); } int64_t most_frequent_dim = std::distance( frequency.begin(), std::max_element(frequency.begin(), frequency.end())); return most_frequent_dim < min_rank ? most_frequent_dim : 0; } absl::Status CombineAllGathers(absl::Span<HloInstruction* const> to_combine, bool combine_by_dim) { if (to_combine.size() < 2) { return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; HloComputation& computation = *to_combine.back()->parent(); // Create a single bigger AllGather of the operands of the smaller AllGather. std::vector<HloInstruction*> operands; std::vector<std::optional<std::vector<int64_t>>> operand_permutations; std::vector<Shape> output_shapes; // Find the most frequent all-gather dimension. int64_t most_frequent_dim = FindMostFrequentGatherDim(to_combine); VLOG(1) << "Combining set"; for (HloInstruction* hlo : to_combine) { VLOG(1) << "Set element: " << hlo->ToString(); TF_RET_CHECK(hlo->opcode() == HloOpcode::kAllGather); const auto* ag = Cast<HloAllGatherInstruction>(hlo); TF_RET_CHECK(hlo->operand_count() == 1); TF_RET_CHECK(hlo->shape().IsArray()); TF_RET_CHECK(!combine_by_dim || ag->all_gather_dimension() == most_frequent_dim); HloInstruction* operand = hlo->operands().front(); operands.push_back(operand); operand_permutations.emplace_back(); output_shapes.push_back(hlo->shape()); // Bitcast operand if needed. if (ag->all_gather_dimension() != most_frequent_dim) { const Shape& operand_shape = operand->shape(); // Build permutation to align gather dimension. auto& perm = operand_permutations.back(); perm = std::vector<int64_t>(operand_shape.rank()); std::iota(perm->begin(), perm->end(), 0); std::swap((*perm)[most_frequent_dim], (*perm)[ag->all_gather_dimension()]); // Bitcast operand and update output shape. operands.back() = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*perm, operand_shape), operand)); output_shapes.back() = ShapeUtil::PermuteDimensions(*perm, hlo->shape()); } } // Create combined all-gather op with a tuple result. HloInstruction* combined; combined = computation.AddInstruction(HloInstruction::CreateAllGather( ShapeUtil::MakeTupleShape(output_shapes), operands, most_frequent_dim, to_combine.front()->device_list(), /*constrain_layout=*/false, to_combine.front()->channel_id(), Cast<HloAllGatherInstruction>(to_combine.front()) ->use_global_device_ids())); // We have to propagate the sharding manually because Domain instructions are // not guaranteed to preserve it for side effecting instructions. combined->set_sharding( hlo_sharding_util::CreateTupleSharding(combined->shape(), to_combine)); VLOG(1) << "Replacing with : " << combined->ToString(); // Replace all the smaller all-gather ops with (bitcast) elements of the tuple // result. for (int64_t i = 0; i < to_combine.size(); ++i) { HloInstruction* replacement = computation.AddInstruction( HloInstruction::CreateGetTupleElement(combined, i)); if (operand_permutations[i]) { replacement = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*operand_permutations[i], replacement->shape()), replacement)); } TF_RETURN_IF_ERROR( computation.ReplaceInstruction(to_combine[i], replacement)); } return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; VLOG(1) << "Combining set"; VLOG(1) << "Set element: " << hlo->ToString(); VLOG(1) << "Replacing with : " << combined->ToString(); std::optional<GroupKey> CombineKey(const HloInstruction* instruction, const HloDomainMap& domain_map, bool combine_by_dim) { if (instruction->opcode() != HloOpcode::kAllGather) { return std::nullopt; } std::vector<std::vector<int64_t>> replica_groups; const auto* ag = Cast<HloAllGatherInstruction>(instruction); replica_groups.reserve(ag->replica_groups().size()); for (const ReplicaGroup& replica_group : ag->replica_groups()) { replica_groups.push_back( std::vector<int64_t>(replica_group.replica_ids().begin(), replica_group.replica_ids().end())); } // Ignore dimension (set to -1) if we are not grouping by dimension. int64_t ag_dim_key = combine_by_dim ? ag->all_gather_dimension() : -1; return GroupKey{ag_dim_key, domain_map.GetDomainMetadataId(ag), ag->channel_id().has_value(), ag->use_global_device_ids(), replica_groups}; } AllGatherCombiner::AllGatherCombiner(int64_t combine_threshold_in_bytes, int64_t combine_threshold_count, bool combine_by_dim) : combine_threshold_in_bytes_(combine_threshold_in_bytes), combine_threshold_count_(combine_threshold_count), combine_by_dim_(combine_by_dim) {} absl::StatusOr<bool> AllGatherCombiner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { VLOG(1) << "Running AllGatherCombiner with threshold of " << combine_threshold_in_bytes_ << " bytes"; if (combine_threshold_in_bytes_ <= 0 || combine_threshold_count_ <= 0) { VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; return false; } if (hlo_query::ContainsLayoutConstrainedCollective(*module, HloOpcode::kAllGather)) { VLOG(1) << "Skip AllGatherCombiner because the module contains " "all-gather with constrained layouts"; return false; } bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, "")); auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); }; auto combine_fn = [&](absl::Span<HloInstruction* const> to_combine) -> absl::Status { return CombineAllGathers(to_combine, combine_by_dim_); }; TF_ASSIGN_OR_RETURN( bool computation_changed, CombineInstructionsByKey<GroupKey>(computation, key_fn, combine_fn, combine_threshold_in_bytes_, combine_threshold_count_)); changed |= computation_changed; } return changed; } VLOG(1) << "Running AllGatherCombiner with threshold of " VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; VLOG(1) << "Skip AllGatherCombiner because the module contains " auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); };
#include "xla/service/all_gather_combiner.h" #include <cstdint> #include <memory> #include <vector> #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" TEST_F(AllGatherCombinerTest, CombineAllGathersByDim) { const char* const hlo_string = R"( HloModule Module ENTRY entry { param0 = f32[2,7]{1,0} parameter(0) param1 = f32[3,8]{1,0} parameter(1) param2 = f32[4,9]{0,1} parameter(2) param3 = f32[5,10]{0,1} parameter(3) param4 = f32[6,11]{1,0} parameter(4) allgather0 = f32[8,7]{1,0} all-gather(param0), replica_groups={}, dimensions={0} allgather1 = f32[12,8]{1,0} all-gather(param1), replica_groups={}, dimensions={0} allgather2 = f32[4,36]{0,1} all-gather(param2), replica_groups={}, dimensions={1} allgather3 = f32[5,40]{0,1} all-gather(param3), replica_groups={}, dimensions={1} allgather4 = f32[24,11]{1,0} all-gather(param4), replica_groups={}, dimensions={0} ROOT tuple = (f32[8,7]{1,0}, f32[12,8]{1,0}, f32[4,36]{0,1}, f32[5,40]{0,1}, f32[24,11]{1,0}) tuple(allgather0, allgather1, allgather2, allgather3, allgather4) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(hlo_string)); AllGatherCombiner combine(1024 * 1024, kMaxCombineCount, /*combine_by_dim=*/true); ASSERT_EQ(AllGatherCount(*module), 5); TF_ASSERT_OK_AND_ASSIGN(bool changed, combine.Run(module.get())); EXPECT_TRUE(changed); Matcher<const HloInstruction*> combined_all_gather_0 = op::AllGather(op::Parameter(0), op::Parameter(1), op::Parameter(4)); Matcher<const HloInstruction*> combined_all_gather_1 = op::AllGather(op::Parameter(2), op::Parameter(3)); EXPECT_THAT(module->entry_computation()->root_instruction(), op::Tuple(op::GetTupleElement(combined_all_gather_0, 0), op::GetTupleElement(combined_all_gather_0, 1), op::GetTupleElement(combined_all_gather_1, 0), op::GetTupleElement(combined_all_gather_1, 1), op::GetTupleElement(combined_all_gather_0, 2))); std::vector<HloAllGatherInstruction*> all_gathers = FindAllGathers(*module); ASSERT_EQ(2, all_gathers.size()); ASSERT_EQ(0, all_gathers[0]->all_gather_dimension()); ASSERT_EQ(1, all_gathers[1]->all_gather_dimension()); }
AllGatherCombinerTest_CombineAllGathersDifferentDims
xla/service/all_gather_combiner_test.cc
int64_t FindMostFrequentGatherDim( absl::Span<HloInstruction* const> to_combine) { assert(!to_combine.empty()); // Count frequencies. int64_t min_rank = std::numeric_limits<int64_t>::max(); std::vector<int64_t> frequency; for (const HloInstruction* it : to_combine) { int64_t dim = Cast<HloAllGatherInstruction>(it)->all_gather_dimension(); frequency.resize(std::max(dim + 1, static_cast<int64_t>(frequency.size())), 0); frequency[dim]++; min_rank = std::min(min_rank, it->shape().rank()); } int64_t most_frequent_dim = std::distance( frequency.begin(), std::max_element(frequency.begin(), frequency.end())); return most_frequent_dim < min_rank ? most_frequent_dim : 0; } absl::Status CombineAllGathers(absl::Span<HloInstruction* const> to_combine, bool combine_by_dim) { if (to_combine.size() < 2) { return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; HloComputation& computation = *to_combine.back()->parent(); // Create a single bigger AllGather of the operands of the smaller AllGather. std::vector<HloInstruction*> operands; std::vector<std::optional<std::vector<int64_t>>> operand_permutations; std::vector<Shape> output_shapes; // Find the most frequent all-gather dimension. int64_t most_frequent_dim = FindMostFrequentGatherDim(to_combine); VLOG(1) << "Combining set"; for (HloInstruction* hlo : to_combine) { VLOG(1) << "Set element: " << hlo->ToString(); TF_RET_CHECK(hlo->opcode() == HloOpcode::kAllGather); const auto* ag = Cast<HloAllGatherInstruction>(hlo); TF_RET_CHECK(hlo->operand_count() == 1); TF_RET_CHECK(hlo->shape().IsArray()); TF_RET_CHECK(!combine_by_dim || ag->all_gather_dimension() == most_frequent_dim); HloInstruction* operand = hlo->operands().front(); operands.push_back(operand); operand_permutations.emplace_back(); output_shapes.push_back(hlo->shape()); // Bitcast operand if needed. if (ag->all_gather_dimension() != most_frequent_dim) { const Shape& operand_shape = operand->shape(); // Build permutation to align gather dimension. auto& perm = operand_permutations.back(); perm = std::vector<int64_t>(operand_shape.rank()); std::iota(perm->begin(), perm->end(), 0); std::swap((*perm)[most_frequent_dim], (*perm)[ag->all_gather_dimension()]); // Bitcast operand and update output shape. operands.back() = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*perm, operand_shape), operand)); output_shapes.back() = ShapeUtil::PermuteDimensions(*perm, hlo->shape()); } } // Create combined all-gather op with a tuple result. HloInstruction* combined; combined = computation.AddInstruction(HloInstruction::CreateAllGather( ShapeUtil::MakeTupleShape(output_shapes), operands, most_frequent_dim, to_combine.front()->device_list(), /*constrain_layout=*/false, to_combine.front()->channel_id(), Cast<HloAllGatherInstruction>(to_combine.front()) ->use_global_device_ids())); // We have to propagate the sharding manually because Domain instructions are // not guaranteed to preserve it for side effecting instructions. combined->set_sharding( hlo_sharding_util::CreateTupleSharding(combined->shape(), to_combine)); VLOG(1) << "Replacing with : " << combined->ToString(); // Replace all the smaller all-gather ops with (bitcast) elements of the tuple // result. for (int64_t i = 0; i < to_combine.size(); ++i) { HloInstruction* replacement = computation.AddInstruction( HloInstruction::CreateGetTupleElement(combined, i)); if (operand_permutations[i]) { replacement = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*operand_permutations[i], replacement->shape()), replacement)); } TF_RETURN_IF_ERROR( computation.ReplaceInstruction(to_combine[i], replacement)); } return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; VLOG(1) << "Combining set"; VLOG(1) << "Set element: " << hlo->ToString(); VLOG(1) << "Replacing with : " << combined->ToString(); std::optional<GroupKey> CombineKey(const HloInstruction* instruction, const HloDomainMap& domain_map, bool combine_by_dim) { if (instruction->opcode() != HloOpcode::kAllGather) { return std::nullopt; } std::vector<std::vector<int64_t>> replica_groups; const auto* ag = Cast<HloAllGatherInstruction>(instruction); replica_groups.reserve(ag->replica_groups().size()); for (const ReplicaGroup& replica_group : ag->replica_groups()) { replica_groups.push_back( std::vector<int64_t>(replica_group.replica_ids().begin(), replica_group.replica_ids().end())); } // Ignore dimension (set to -1) if we are not grouping by dimension. int64_t ag_dim_key = combine_by_dim ? ag->all_gather_dimension() : -1; return GroupKey{ag_dim_key, domain_map.GetDomainMetadataId(ag), ag->channel_id().has_value(), ag->use_global_device_ids(), replica_groups}; } AllGatherCombiner::AllGatherCombiner(int64_t combine_threshold_in_bytes, int64_t combine_threshold_count, bool combine_by_dim) : combine_threshold_in_bytes_(combine_threshold_in_bytes), combine_threshold_count_(combine_threshold_count), combine_by_dim_(combine_by_dim) {} absl::StatusOr<bool> AllGatherCombiner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { VLOG(1) << "Running AllGatherCombiner with threshold of " << combine_threshold_in_bytes_ << " bytes"; if (combine_threshold_in_bytes_ <= 0 || combine_threshold_count_ <= 0) { VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; return false; } if (hlo_query::ContainsLayoutConstrainedCollective(*module, HloOpcode::kAllGather)) { VLOG(1) << "Skip AllGatherCombiner because the module contains " "all-gather with constrained layouts"; return false; } bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, "")); auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); }; auto combine_fn = [&](absl::Span<HloInstruction* const> to_combine) -> absl::Status { return CombineAllGathers(to_combine, combine_by_dim_); }; TF_ASSIGN_OR_RETURN( bool computation_changed, CombineInstructionsByKey<GroupKey>(computation, key_fn, combine_fn, combine_threshold_in_bytes_, combine_threshold_count_)); changed |= computation_changed; } return changed; } VLOG(1) << "Running AllGatherCombiner with threshold of " VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; VLOG(1) << "Skip AllGatherCombiner because the module contains " auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); };
#include "xla/service/all_gather_combiner.h" #include <cstdint> #include <memory> #include <vector> #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" TEST_F(AllGatherCombinerTest, CombineAllGathersDifferentDims) { const char* const hlo_string = R"( HloModule Module ENTRY entry { param0 = f32[2,3]{1,0} parameter(0) param1 = f32[2,3]{0,1} parameter(1) allgather0 = f32[8,3]{1,0} all-gather(param0), replica_groups={}, dimensions={0} allgather1 = f32[2,12]{0,1} all-gather(param1), replica_groups={}, dimensions={1} ROOT tuple = (f32[8,3]{1,0}, f32[2,12]{0,1}) tuple(allgather0, allgather1) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(hlo_string)); AllGatherCombiner combine(1024 * 1024, kMaxCombineCount, /*combine_by_dim=*/false); ASSERT_EQ(AllGatherCount(*module), 2); TF_ASSERT_OK_AND_ASSIGN(bool changed, combine.Run(module.get())); EXPECT_TRUE(changed); Matcher<const HloInstruction*> combined_all_gather = op::AllGather(op::Parameter(0), op::Bitcast(op::Parameter(1))); EXPECT_THAT( module->entry_computation()->root_instruction(), op::Tuple(op::GetTupleElement(combined_all_gather, 0), op::Bitcast(op::GetTupleElement(combined_all_gather, 1)))); }
AllGatherCombinerTest_CombineFromTwoDomainsWithSameMetadata
xla/service/all_gather_combiner_test.cc
int64_t FindMostFrequentGatherDim( absl::Span<HloInstruction* const> to_combine) { assert(!to_combine.empty()); // Count frequencies. int64_t min_rank = std::numeric_limits<int64_t>::max(); std::vector<int64_t> frequency; for (const HloInstruction* it : to_combine) { int64_t dim = Cast<HloAllGatherInstruction>(it)->all_gather_dimension(); frequency.resize(std::max(dim + 1, static_cast<int64_t>(frequency.size())), 0); frequency[dim]++; min_rank = std::min(min_rank, it->shape().rank()); } int64_t most_frequent_dim = std::distance( frequency.begin(), std::max_element(frequency.begin(), frequency.end())); return most_frequent_dim < min_rank ? most_frequent_dim : 0; } absl::Status CombineAllGathers(absl::Span<HloInstruction* const> to_combine, bool combine_by_dim) { if (to_combine.size() < 2) { return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; HloComputation& computation = *to_combine.back()->parent(); // Create a single bigger AllGather of the operands of the smaller AllGather. std::vector<HloInstruction*> operands; std::vector<std::optional<std::vector<int64_t>>> operand_permutations; std::vector<Shape> output_shapes; // Find the most frequent all-gather dimension. int64_t most_frequent_dim = FindMostFrequentGatherDim(to_combine); VLOG(1) << "Combining set"; for (HloInstruction* hlo : to_combine) { VLOG(1) << "Set element: " << hlo->ToString(); TF_RET_CHECK(hlo->opcode() == HloOpcode::kAllGather); const auto* ag = Cast<HloAllGatherInstruction>(hlo); TF_RET_CHECK(hlo->operand_count() == 1); TF_RET_CHECK(hlo->shape().IsArray()); TF_RET_CHECK(!combine_by_dim || ag->all_gather_dimension() == most_frequent_dim); HloInstruction* operand = hlo->operands().front(); operands.push_back(operand); operand_permutations.emplace_back(); output_shapes.push_back(hlo->shape()); // Bitcast operand if needed. if (ag->all_gather_dimension() != most_frequent_dim) { const Shape& operand_shape = operand->shape(); // Build permutation to align gather dimension. auto& perm = operand_permutations.back(); perm = std::vector<int64_t>(operand_shape.rank()); std::iota(perm->begin(), perm->end(), 0); std::swap((*perm)[most_frequent_dim], (*perm)[ag->all_gather_dimension()]); // Bitcast operand and update output shape. operands.back() = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*perm, operand_shape), operand)); output_shapes.back() = ShapeUtil::PermuteDimensions(*perm, hlo->shape()); } } // Create combined all-gather op with a tuple result. HloInstruction* combined; combined = computation.AddInstruction(HloInstruction::CreateAllGather( ShapeUtil::MakeTupleShape(output_shapes), operands, most_frequent_dim, to_combine.front()->device_list(), /*constrain_layout=*/false, to_combine.front()->channel_id(), Cast<HloAllGatherInstruction>(to_combine.front()) ->use_global_device_ids())); // We have to propagate the sharding manually because Domain instructions are // not guaranteed to preserve it for side effecting instructions. combined->set_sharding( hlo_sharding_util::CreateTupleSharding(combined->shape(), to_combine)); VLOG(1) << "Replacing with : " << combined->ToString(); // Replace all the smaller all-gather ops with (bitcast) elements of the tuple // result. for (int64_t i = 0; i < to_combine.size(); ++i) { HloInstruction* replacement = computation.AddInstruction( HloInstruction::CreateGetTupleElement(combined, i)); if (operand_permutations[i]) { replacement = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*operand_permutations[i], replacement->shape()), replacement)); } TF_RETURN_IF_ERROR( computation.ReplaceInstruction(to_combine[i], replacement)); } return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; VLOG(1) << "Combining set"; VLOG(1) << "Set element: " << hlo->ToString(); VLOG(1) << "Replacing with : " << combined->ToString(); std::optional<GroupKey> CombineKey(const HloInstruction* instruction, const HloDomainMap& domain_map, bool combine_by_dim) { if (instruction->opcode() != HloOpcode::kAllGather) { return std::nullopt; } std::vector<std::vector<int64_t>> replica_groups; const auto* ag = Cast<HloAllGatherInstruction>(instruction); replica_groups.reserve(ag->replica_groups().size()); for (const ReplicaGroup& replica_group : ag->replica_groups()) { replica_groups.push_back( std::vector<int64_t>(replica_group.replica_ids().begin(), replica_group.replica_ids().end())); } // Ignore dimension (set to -1) if we are not grouping by dimension. int64_t ag_dim_key = combine_by_dim ? ag->all_gather_dimension() : -1; return GroupKey{ag_dim_key, domain_map.GetDomainMetadataId(ag), ag->channel_id().has_value(), ag->use_global_device_ids(), replica_groups}; } AllGatherCombiner::AllGatherCombiner(int64_t combine_threshold_in_bytes, int64_t combine_threshold_count, bool combine_by_dim) : combine_threshold_in_bytes_(combine_threshold_in_bytes), combine_threshold_count_(combine_threshold_count), combine_by_dim_(combine_by_dim) {} absl::StatusOr<bool> AllGatherCombiner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { VLOG(1) << "Running AllGatherCombiner with threshold of " << combine_threshold_in_bytes_ << " bytes"; if (combine_threshold_in_bytes_ <= 0 || combine_threshold_count_ <= 0) { VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; return false; } if (hlo_query::ContainsLayoutConstrainedCollective(*module, HloOpcode::kAllGather)) { VLOG(1) << "Skip AllGatherCombiner because the module contains " "all-gather with constrained layouts"; return false; } bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, "")); auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); }; auto combine_fn = [&](absl::Span<HloInstruction* const> to_combine) -> absl::Status { return CombineAllGathers(to_combine, combine_by_dim_); }; TF_ASSIGN_OR_RETURN( bool computation_changed, CombineInstructionsByKey<GroupKey>(computation, key_fn, combine_fn, combine_threshold_in_bytes_, combine_threshold_count_)); changed |= computation_changed; } return changed; } VLOG(1) << "Running AllGatherCombiner with threshold of " VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; VLOG(1) << "Skip AllGatherCombiner because the module contains " auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); };
#include "xla/service/all_gather_combiner.h" #include <cstdint> #include <memory> #include <vector> #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h"
AllGatherCombinerTest_CombineManyAllGathersDifferentDims
xla/service/all_gather_combiner_test.cc
int64_t FindMostFrequentGatherDim( absl::Span<HloInstruction* const> to_combine) { assert(!to_combine.empty()); // Count frequencies. int64_t min_rank = std::numeric_limits<int64_t>::max(); std::vector<int64_t> frequency; for (const HloInstruction* it : to_combine) { int64_t dim = Cast<HloAllGatherInstruction>(it)->all_gather_dimension(); frequency.resize(std::max(dim + 1, static_cast<int64_t>(frequency.size())), 0); frequency[dim]++; min_rank = std::min(min_rank, it->shape().rank()); } int64_t most_frequent_dim = std::distance( frequency.begin(), std::max_element(frequency.begin(), frequency.end())); return most_frequent_dim < min_rank ? most_frequent_dim : 0; } absl::Status CombineAllGathers(absl::Span<HloInstruction* const> to_combine, bool combine_by_dim) { if (to_combine.size() < 2) { return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; HloComputation& computation = *to_combine.back()->parent(); // Create a single bigger AllGather of the operands of the smaller AllGather. std::vector<HloInstruction*> operands; std::vector<std::optional<std::vector<int64_t>>> operand_permutations; std::vector<Shape> output_shapes; // Find the most frequent all-gather dimension. int64_t most_frequent_dim = FindMostFrequentGatherDim(to_combine); VLOG(1) << "Combining set"; for (HloInstruction* hlo : to_combine) { VLOG(1) << "Set element: " << hlo->ToString(); TF_RET_CHECK(hlo->opcode() == HloOpcode::kAllGather); const auto* ag = Cast<HloAllGatherInstruction>(hlo); TF_RET_CHECK(hlo->operand_count() == 1); TF_RET_CHECK(hlo->shape().IsArray()); TF_RET_CHECK(!combine_by_dim || ag->all_gather_dimension() == most_frequent_dim); HloInstruction* operand = hlo->operands().front(); operands.push_back(operand); operand_permutations.emplace_back(); output_shapes.push_back(hlo->shape()); // Bitcast operand if needed. if (ag->all_gather_dimension() != most_frequent_dim) { const Shape& operand_shape = operand->shape(); // Build permutation to align gather dimension. auto& perm = operand_permutations.back(); perm = std::vector<int64_t>(operand_shape.rank()); std::iota(perm->begin(), perm->end(), 0); std::swap((*perm)[most_frequent_dim], (*perm)[ag->all_gather_dimension()]); // Bitcast operand and update output shape. operands.back() = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*perm, operand_shape), operand)); output_shapes.back() = ShapeUtil::PermuteDimensions(*perm, hlo->shape()); } } // Create combined all-gather op with a tuple result. HloInstruction* combined; combined = computation.AddInstruction(HloInstruction::CreateAllGather( ShapeUtil::MakeTupleShape(output_shapes), operands, most_frequent_dim, to_combine.front()->device_list(), /*constrain_layout=*/false, to_combine.front()->channel_id(), Cast<HloAllGatherInstruction>(to_combine.front()) ->use_global_device_ids())); // We have to propagate the sharding manually because Domain instructions are // not guaranteed to preserve it for side effecting instructions. combined->set_sharding( hlo_sharding_util::CreateTupleSharding(combined->shape(), to_combine)); VLOG(1) << "Replacing with : " << combined->ToString(); // Replace all the smaller all-gather ops with (bitcast) elements of the tuple // result. for (int64_t i = 0; i < to_combine.size(); ++i) { HloInstruction* replacement = computation.AddInstruction( HloInstruction::CreateGetTupleElement(combined, i)); if (operand_permutations[i]) { replacement = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*operand_permutations[i], replacement->shape()), replacement)); } TF_RETURN_IF_ERROR( computation.ReplaceInstruction(to_combine[i], replacement)); } return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; VLOG(1) << "Combining set"; VLOG(1) << "Set element: " << hlo->ToString(); VLOG(1) << "Replacing with : " << combined->ToString(); std::optional<GroupKey> CombineKey(const HloInstruction* instruction, const HloDomainMap& domain_map, bool combine_by_dim) { if (instruction->opcode() != HloOpcode::kAllGather) { return std::nullopt; } std::vector<std::vector<int64_t>> replica_groups; const auto* ag = Cast<HloAllGatherInstruction>(instruction); replica_groups.reserve(ag->replica_groups().size()); for (const ReplicaGroup& replica_group : ag->replica_groups()) { replica_groups.push_back( std::vector<int64_t>(replica_group.replica_ids().begin(), replica_group.replica_ids().end())); } // Ignore dimension (set to -1) if we are not grouping by dimension. int64_t ag_dim_key = combine_by_dim ? ag->all_gather_dimension() : -1; return GroupKey{ag_dim_key, domain_map.GetDomainMetadataId(ag), ag->channel_id().has_value(), ag->use_global_device_ids(), replica_groups}; } AllGatherCombiner::AllGatherCombiner(int64_t combine_threshold_in_bytes, int64_t combine_threshold_count, bool combine_by_dim) : combine_threshold_in_bytes_(combine_threshold_in_bytes), combine_threshold_count_(combine_threshold_count), combine_by_dim_(combine_by_dim) {} absl::StatusOr<bool> AllGatherCombiner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { VLOG(1) << "Running AllGatherCombiner with threshold of " << combine_threshold_in_bytes_ << " bytes"; if (combine_threshold_in_bytes_ <= 0 || combine_threshold_count_ <= 0) { VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; return false; } if (hlo_query::ContainsLayoutConstrainedCollective(*module, HloOpcode::kAllGather)) { VLOG(1) << "Skip AllGatherCombiner because the module contains " "all-gather with constrained layouts"; return false; } bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, "")); auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); }; auto combine_fn = [&](absl::Span<HloInstruction* const> to_combine) -> absl::Status { return CombineAllGathers(to_combine, combine_by_dim_); }; TF_ASSIGN_OR_RETURN( bool computation_changed, CombineInstructionsByKey<GroupKey>(computation, key_fn, combine_fn, combine_threshold_in_bytes_, combine_threshold_count_)); changed |= computation_changed; } return changed; } VLOG(1) << "Running AllGatherCombiner with threshold of " VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; VLOG(1) << "Skip AllGatherCombiner because the module contains " auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); };
#include "xla/service/all_gather_combiner.h" #include <cstdint> #include <memory> #include <vector> #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" TEST_F(AllGatherCombinerTest, CombineManyAllGathersDifferentDims) { const char* const hlo_string = R"( HloModule Module ENTRY entry { param0 = f32[2,7]{1,0} parameter(0) param1 = f32[3,8]{1,0} parameter(1) param2 = f32[4,9]{0,1} parameter(2) param3 = f32[5,10]{0,1} parameter(3) param4 = f32[6,11]{1,0} parameter(4) allgather0 = f32[8,7]{1,0} all-gather(param0), replica_groups={}, dimensions={0} allgather1 = f32[12,8]{1,0} all-gather(param1), replica_groups={}, dimensions={0} allgather2 = f32[4,36]{0,1} all-gather(param2), replica_groups={}, dimensions={1} allgather3 = f32[5,40]{0,1} all-gather(param3), replica_groups={}, dimensions={1} allgather4 = f32[24,11]{1,0} all-gather(param4), replica_groups={}, dimensions={0} ROOT tuple = (f32[8,7]{1,0}, f32[12,8]{1,0}, f32[4,36]{0,1}, f32[5,40]{0,1}, f32[24,11]{1,0}) tuple(allgather0, allgather1, allgather2, allgather3, allgather4) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(hlo_string)); AllGatherCombiner combine(1024 * 1024, kMaxCombineCount, /*combine_by_dim=*/false); ASSERT_EQ(AllGatherCount(*module), 5); TF_ASSERT_OK_AND_ASSIGN(bool changed, combine.Run(module.get())); EXPECT_TRUE(changed); Matcher<const HloInstruction*> combined_all_gather = op::AllGather( op::Parameter(0), op::Parameter(1), op::Bitcast(op::Parameter(2)), op::Bitcast(op::Parameter(3)), op::Parameter(4)); EXPECT_THAT( module->entry_computation()->root_instruction(), op::Tuple(op::GetTupleElement(combined_all_gather, 0), op::GetTupleElement(combined_all_gather, 1), op::Bitcast(op::GetTupleElement(combined_all_gather, 2)), op::Bitcast(op::GetTupleElement(combined_all_gather, 3)), op::GetTupleElement(combined_all_gather, 4))); std::vector<HloAllGatherInstruction*> all_gathers = FindAllGathers(*module); ASSERT_EQ(1, all_gathers.size()); ASSERT_EQ(0, all_gathers.front()->all_gather_dimension()); }
AllGatherCombinerTest_CombineManyAllGathersDifferentDimsMixedRanks
xla/service/all_gather_combiner_test.cc
int64_t FindMostFrequentGatherDim( absl::Span<HloInstruction* const> to_combine) { assert(!to_combine.empty()); // Count frequencies. int64_t min_rank = std::numeric_limits<int64_t>::max(); std::vector<int64_t> frequency; for (const HloInstruction* it : to_combine) { int64_t dim = Cast<HloAllGatherInstruction>(it)->all_gather_dimension(); frequency.resize(std::max(dim + 1, static_cast<int64_t>(frequency.size())), 0); frequency[dim]++; min_rank = std::min(min_rank, it->shape().rank()); } int64_t most_frequent_dim = std::distance( frequency.begin(), std::max_element(frequency.begin(), frequency.end())); return most_frequent_dim < min_rank ? most_frequent_dim : 0; } absl::Status CombineAllGathers(absl::Span<HloInstruction* const> to_combine, bool combine_by_dim) { if (to_combine.size() < 2) { return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; HloComputation& computation = *to_combine.back()->parent(); // Create a single bigger AllGather of the operands of the smaller AllGather. std::vector<HloInstruction*> operands; std::vector<std::optional<std::vector<int64_t>>> operand_permutations; std::vector<Shape> output_shapes; // Find the most frequent all-gather dimension. int64_t most_frequent_dim = FindMostFrequentGatherDim(to_combine); VLOG(1) << "Combining set"; for (HloInstruction* hlo : to_combine) { VLOG(1) << "Set element: " << hlo->ToString(); TF_RET_CHECK(hlo->opcode() == HloOpcode::kAllGather); const auto* ag = Cast<HloAllGatherInstruction>(hlo); TF_RET_CHECK(hlo->operand_count() == 1); TF_RET_CHECK(hlo->shape().IsArray()); TF_RET_CHECK(!combine_by_dim || ag->all_gather_dimension() == most_frequent_dim); HloInstruction* operand = hlo->operands().front(); operands.push_back(operand); operand_permutations.emplace_back(); output_shapes.push_back(hlo->shape()); // Bitcast operand if needed. if (ag->all_gather_dimension() != most_frequent_dim) { const Shape& operand_shape = operand->shape(); // Build permutation to align gather dimension. auto& perm = operand_permutations.back(); perm = std::vector<int64_t>(operand_shape.rank()); std::iota(perm->begin(), perm->end(), 0); std::swap((*perm)[most_frequent_dim], (*perm)[ag->all_gather_dimension()]); // Bitcast operand and update output shape. operands.back() = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*perm, operand_shape), operand)); output_shapes.back() = ShapeUtil::PermuteDimensions(*perm, hlo->shape()); } } // Create combined all-gather op with a tuple result. HloInstruction* combined; combined = computation.AddInstruction(HloInstruction::CreateAllGather( ShapeUtil::MakeTupleShape(output_shapes), operands, most_frequent_dim, to_combine.front()->device_list(), /*constrain_layout=*/false, to_combine.front()->channel_id(), Cast<HloAllGatherInstruction>(to_combine.front()) ->use_global_device_ids())); // We have to propagate the sharding manually because Domain instructions are // not guaranteed to preserve it for side effecting instructions. combined->set_sharding( hlo_sharding_util::CreateTupleSharding(combined->shape(), to_combine)); VLOG(1) << "Replacing with : " << combined->ToString(); // Replace all the smaller all-gather ops with (bitcast) elements of the tuple // result. for (int64_t i = 0; i < to_combine.size(); ++i) { HloInstruction* replacement = computation.AddInstruction( HloInstruction::CreateGetTupleElement(combined, i)); if (operand_permutations[i]) { replacement = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*operand_permutations[i], replacement->shape()), replacement)); } TF_RETURN_IF_ERROR( computation.ReplaceInstruction(to_combine[i], replacement)); } return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; VLOG(1) << "Combining set"; VLOG(1) << "Set element: " << hlo->ToString(); VLOG(1) << "Replacing with : " << combined->ToString(); std::optional<GroupKey> CombineKey(const HloInstruction* instruction, const HloDomainMap& domain_map, bool combine_by_dim) { if (instruction->opcode() != HloOpcode::kAllGather) { return std::nullopt; } std::vector<std::vector<int64_t>> replica_groups; const auto* ag = Cast<HloAllGatherInstruction>(instruction); replica_groups.reserve(ag->replica_groups().size()); for (const ReplicaGroup& replica_group : ag->replica_groups()) { replica_groups.push_back( std::vector<int64_t>(replica_group.replica_ids().begin(), replica_group.replica_ids().end())); } // Ignore dimension (set to -1) if we are not grouping by dimension. int64_t ag_dim_key = combine_by_dim ? ag->all_gather_dimension() : -1; return GroupKey{ag_dim_key, domain_map.GetDomainMetadataId(ag), ag->channel_id().has_value(), ag->use_global_device_ids(), replica_groups}; } AllGatherCombiner::AllGatherCombiner(int64_t combine_threshold_in_bytes, int64_t combine_threshold_count, bool combine_by_dim) : combine_threshold_in_bytes_(combine_threshold_in_bytes), combine_threshold_count_(combine_threshold_count), combine_by_dim_(combine_by_dim) {} absl::StatusOr<bool> AllGatherCombiner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { VLOG(1) << "Running AllGatherCombiner with threshold of " << combine_threshold_in_bytes_ << " bytes"; if (combine_threshold_in_bytes_ <= 0 || combine_threshold_count_ <= 0) { VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; return false; } if (hlo_query::ContainsLayoutConstrainedCollective(*module, HloOpcode::kAllGather)) { VLOG(1) << "Skip AllGatherCombiner because the module contains " "all-gather with constrained layouts"; return false; } bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, "")); auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); }; auto combine_fn = [&](absl::Span<HloInstruction* const> to_combine) -> absl::Status { return CombineAllGathers(to_combine, combine_by_dim_); }; TF_ASSIGN_OR_RETURN( bool computation_changed, CombineInstructionsByKey<GroupKey>(computation, key_fn, combine_fn, combine_threshold_in_bytes_, combine_threshold_count_)); changed |= computation_changed; } return changed; } VLOG(1) << "Running AllGatherCombiner with threshold of " VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; VLOG(1) << "Skip AllGatherCombiner because the module contains " auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); };
#include "xla/service/all_gather_combiner.h" #include <cstdint> #include <memory> #include <vector> #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" TEST_F(AllGatherCombinerTest, CombineManyAllGathersDifferentDimsMixedRanks) { const char* const hlo_string = R"( HloModule Module ENTRY entry { param0 = f32[2,7]{1,0} parameter(0) param1 = f32[3,8]{1,0} parameter(1) param2 = f32[4,9]{0,1} parameter(2) param3 = f32[5,10]{0,1} parameter(3) param4 = f32[6]{0} parameter(4) allgather0 = f32[2,28]{1,0} all-gather(param0), replica_groups={}, dimensions={1} allgather1 = f32[3,32]{1,0} all-gather(param1), replica_groups={}, dimensions={1} allgather2 = f32[4,36]{0,1} all-gather(param2), replica_groups={}, dimensions={1} allgather3 = f32[5,40]{0,1} all-gather(param3), replica_groups={}, dimensions={1} allgather4 = f32[24]{0} all-gather(param4), replica_groups={}, dimensions={0} ROOT tuple = (f32[2,28]{1,0}, f32[3,32]{1,0}, f32[4,36]{0,1}, f32[5,40]{0,1}, f32[24]{0}) tuple(allgather0, allgather1, allgather2, allgather3, allgather4) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(hlo_string)); AllGatherCombiner combine(1024 * 1024, kMaxCombineCount, /*combine_by_dim=*/false); ASSERT_EQ(AllGatherCount(*module), 5); TF_ASSERT_OK_AND_ASSIGN(bool changed, combine.Run(module.get())); EXPECT_TRUE(changed); Matcher<const HloInstruction*> combined_all_gather = op::AllGather( op::Bitcast(op::Parameter(0)), op::Bitcast(op::Parameter(1)), op::Bitcast(op::Parameter(2)), op::Bitcast(op::Parameter(3)), op::Parameter(4)); EXPECT_THAT( module->entry_computation()->root_instruction(), op::Tuple(op::Bitcast(op::GetTupleElement(combined_all_gather, 0)), op::Bitcast(op::GetTupleElement(combined_all_gather, 1)), op::Bitcast(op::GetTupleElement(combined_all_gather, 2)), op::Bitcast(op::GetTupleElement(combined_all_gather, 3)), op::GetTupleElement(combined_all_gather, 4))); std::vector<HloAllGatherInstruction*> all_gathers = FindAllGathers(*module); ASSERT_EQ(1, all_gathers.size()); // when using different ranks and the most frequent AG dim (1) is not valid // for rank 1 shape, we use default dim 0. ASSERT_EQ(0, all_gathers.front()->all_gather_dimension()); }
AllGatherCombinerTest_CombineManyAllGathersDifferentDimsRank4
xla/service/all_gather_combiner_test.cc
int64_t FindMostFrequentGatherDim( absl::Span<HloInstruction* const> to_combine) { assert(!to_combine.empty()); // Count frequencies. int64_t min_rank = std::numeric_limits<int64_t>::max(); std::vector<int64_t> frequency; for (const HloInstruction* it : to_combine) { int64_t dim = Cast<HloAllGatherInstruction>(it)->all_gather_dimension(); frequency.resize(std::max(dim + 1, static_cast<int64_t>(frequency.size())), 0); frequency[dim]++; min_rank = std::min(min_rank, it->shape().rank()); } int64_t most_frequent_dim = std::distance( frequency.begin(), std::max_element(frequency.begin(), frequency.end())); return most_frequent_dim < min_rank ? most_frequent_dim : 0; } absl::Status CombineAllGathers(absl::Span<HloInstruction* const> to_combine, bool combine_by_dim) { if (to_combine.size() < 2) { return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; HloComputation& computation = *to_combine.back()->parent(); // Create a single bigger AllGather of the operands of the smaller AllGather. std::vector<HloInstruction*> operands; std::vector<std::optional<std::vector<int64_t>>> operand_permutations; std::vector<Shape> output_shapes; // Find the most frequent all-gather dimension. int64_t most_frequent_dim = FindMostFrequentGatherDim(to_combine); VLOG(1) << "Combining set"; for (HloInstruction* hlo : to_combine) { VLOG(1) << "Set element: " << hlo->ToString(); TF_RET_CHECK(hlo->opcode() == HloOpcode::kAllGather); const auto* ag = Cast<HloAllGatherInstruction>(hlo); TF_RET_CHECK(hlo->operand_count() == 1); TF_RET_CHECK(hlo->shape().IsArray()); TF_RET_CHECK(!combine_by_dim || ag->all_gather_dimension() == most_frequent_dim); HloInstruction* operand = hlo->operands().front(); operands.push_back(operand); operand_permutations.emplace_back(); output_shapes.push_back(hlo->shape()); // Bitcast operand if needed. if (ag->all_gather_dimension() != most_frequent_dim) { const Shape& operand_shape = operand->shape(); // Build permutation to align gather dimension. auto& perm = operand_permutations.back(); perm = std::vector<int64_t>(operand_shape.rank()); std::iota(perm->begin(), perm->end(), 0); std::swap((*perm)[most_frequent_dim], (*perm)[ag->all_gather_dimension()]); // Bitcast operand and update output shape. operands.back() = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*perm, operand_shape), operand)); output_shapes.back() = ShapeUtil::PermuteDimensions(*perm, hlo->shape()); } } // Create combined all-gather op with a tuple result. HloInstruction* combined; combined = computation.AddInstruction(HloInstruction::CreateAllGather( ShapeUtil::MakeTupleShape(output_shapes), operands, most_frequent_dim, to_combine.front()->device_list(), /*constrain_layout=*/false, to_combine.front()->channel_id(), Cast<HloAllGatherInstruction>(to_combine.front()) ->use_global_device_ids())); // We have to propagate the sharding manually because Domain instructions are // not guaranteed to preserve it for side effecting instructions. combined->set_sharding( hlo_sharding_util::CreateTupleSharding(combined->shape(), to_combine)); VLOG(1) << "Replacing with : " << combined->ToString(); // Replace all the smaller all-gather ops with (bitcast) elements of the tuple // result. for (int64_t i = 0; i < to_combine.size(); ++i) { HloInstruction* replacement = computation.AddInstruction( HloInstruction::CreateGetTupleElement(combined, i)); if (operand_permutations[i]) { replacement = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*operand_permutations[i], replacement->shape()), replacement)); } TF_RETURN_IF_ERROR( computation.ReplaceInstruction(to_combine[i], replacement)); } return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; VLOG(1) << "Combining set"; VLOG(1) << "Set element: " << hlo->ToString(); VLOG(1) << "Replacing with : " << combined->ToString(); std::optional<GroupKey> CombineKey(const HloInstruction* instruction, const HloDomainMap& domain_map, bool combine_by_dim) { if (instruction->opcode() != HloOpcode::kAllGather) { return std::nullopt; } std::vector<std::vector<int64_t>> replica_groups; const auto* ag = Cast<HloAllGatherInstruction>(instruction); replica_groups.reserve(ag->replica_groups().size()); for (const ReplicaGroup& replica_group : ag->replica_groups()) { replica_groups.push_back( std::vector<int64_t>(replica_group.replica_ids().begin(), replica_group.replica_ids().end())); } // Ignore dimension (set to -1) if we are not grouping by dimension. int64_t ag_dim_key = combine_by_dim ? ag->all_gather_dimension() : -1; return GroupKey{ag_dim_key, domain_map.GetDomainMetadataId(ag), ag->channel_id().has_value(), ag->use_global_device_ids(), replica_groups}; } AllGatherCombiner::AllGatherCombiner(int64_t combine_threshold_in_bytes, int64_t combine_threshold_count, bool combine_by_dim) : combine_threshold_in_bytes_(combine_threshold_in_bytes), combine_threshold_count_(combine_threshold_count), combine_by_dim_(combine_by_dim) {} absl::StatusOr<bool> AllGatherCombiner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { VLOG(1) << "Running AllGatherCombiner with threshold of " << combine_threshold_in_bytes_ << " bytes"; if (combine_threshold_in_bytes_ <= 0 || combine_threshold_count_ <= 0) { VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; return false; } if (hlo_query::ContainsLayoutConstrainedCollective(*module, HloOpcode::kAllGather)) { VLOG(1) << "Skip AllGatherCombiner because the module contains " "all-gather with constrained layouts"; return false; } bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, "")); auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); }; auto combine_fn = [&](absl::Span<HloInstruction* const> to_combine) -> absl::Status { return CombineAllGathers(to_combine, combine_by_dim_); }; TF_ASSIGN_OR_RETURN( bool computation_changed, CombineInstructionsByKey<GroupKey>(computation, key_fn, combine_fn, combine_threshold_in_bytes_, combine_threshold_count_)); changed |= computation_changed; } return changed; } VLOG(1) << "Running AllGatherCombiner with threshold of " VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; VLOG(1) << "Skip AllGatherCombiner because the module contains " auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); };
#include "xla/service/all_gather_combiner.h" #include <cstdint> #include <memory> #include <vector> #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" TEST_F(AllGatherCombinerTest, CombineManyAllGathersDifferentDimsRank4) { const char* const hlo_string = R"( HloModule Module ENTRY entry { param0 = f32[2,7,2,7]{3,2,1,0} parameter(0) param1 = f32[3,8,3,8]{3,2,1,0} parameter(1) param2 = f32[4,9,4,9]{3,0,1,2} parameter(2) param3 = f32[5,10,5,10]{3,0,1,2} parameter(3) param4 = f32[6,11,6,11]{3,2,1,0} parameter(4) allgather0 = f32[8,7,2,7]{3,2,1,0} all-gather(param0), replica_groups={}, dimensions={0} allgather1 = f32[12,8,3,8]{3,2,1,0} all-gather(param1), replica_groups={}, dimensions={0} allgather2 = f32[4,9,16,9]{3,0,1,2} all-gather(param2), replica_groups={}, dimensions={2} allgather3 = f32[5,10,20,10]{3,0,1,2} all-gather(param3), replica_groups={}, dimensions={2} allgather4 = f32[24,11,6,11]{3,2,1,0} all-gather(param4), replica_groups={}, dimensions={0} ROOT tuple = (f32[8,7,2,7]{3,2,1,0}, f32[12,8,3,8]{3,2,1,0}, f32[4,9,16,9]{3,0,1,2}, f32[5,10,20,10]{3,0,1,2}, f32[24,11,6,11]{3,2,1,0}) tuple(allgather0, allgather1, allgather2, allgather3, allgather4) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(hlo_string)); AllGatherCombiner combine(1024 * 1024, kMaxCombineCount, /*combine_by_dim=*/false); ASSERT_EQ(AllGatherCount(*module), 5); TF_ASSERT_OK_AND_ASSIGN(bool changed, combine.Run(module.get())); EXPECT_TRUE(changed); Matcher<const HloInstruction*> combined_all_gather = op::AllGather( op::Parameter(0), op::Parameter(1), op::Bitcast(op::Parameter(2)), op::Bitcast(op::Parameter(3)), op::Parameter(4)); EXPECT_THAT( module->entry_computation()->root_instruction(), op::Tuple(op::GetTupleElement(combined_all_gather, 0), op::GetTupleElement(combined_all_gather, 1), op::Bitcast(op::GetTupleElement(combined_all_gather, 2)), op::Bitcast(op::GetTupleElement(combined_all_gather, 3)), op::GetTupleElement(combined_all_gather, 4))); std::vector<HloAllGatherInstruction*> all_gathers = FindAllGathers(*module); ASSERT_EQ(1, all_gathers.size()); ASSERT_EQ(0, all_gathers.front()->all_gather_dimension()); }
AllGatherCombinerTest_CombineUpToThreshold
xla/service/all_gather_combiner_test.cc
int64_t FindMostFrequentGatherDim( absl::Span<HloInstruction* const> to_combine) { assert(!to_combine.empty()); // Count frequencies. int64_t min_rank = std::numeric_limits<int64_t>::max(); std::vector<int64_t> frequency; for (const HloInstruction* it : to_combine) { int64_t dim = Cast<HloAllGatherInstruction>(it)->all_gather_dimension(); frequency.resize(std::max(dim + 1, static_cast<int64_t>(frequency.size())), 0); frequency[dim]++; min_rank = std::min(min_rank, it->shape().rank()); } int64_t most_frequent_dim = std::distance( frequency.begin(), std::max_element(frequency.begin(), frequency.end())); return most_frequent_dim < min_rank ? most_frequent_dim : 0; } absl::Status CombineAllGathers(absl::Span<HloInstruction* const> to_combine, bool combine_by_dim) { if (to_combine.size() < 2) { return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; HloComputation& computation = *to_combine.back()->parent(); // Create a single bigger AllGather of the operands of the smaller AllGather. std::vector<HloInstruction*> operands; std::vector<std::optional<std::vector<int64_t>>> operand_permutations; std::vector<Shape> output_shapes; // Find the most frequent all-gather dimension. int64_t most_frequent_dim = FindMostFrequentGatherDim(to_combine); VLOG(1) << "Combining set"; for (HloInstruction* hlo : to_combine) { VLOG(1) << "Set element: " << hlo->ToString(); TF_RET_CHECK(hlo->opcode() == HloOpcode::kAllGather); const auto* ag = Cast<HloAllGatherInstruction>(hlo); TF_RET_CHECK(hlo->operand_count() == 1); TF_RET_CHECK(hlo->shape().IsArray()); TF_RET_CHECK(!combine_by_dim || ag->all_gather_dimension() == most_frequent_dim); HloInstruction* operand = hlo->operands().front(); operands.push_back(operand); operand_permutations.emplace_back(); output_shapes.push_back(hlo->shape()); // Bitcast operand if needed. if (ag->all_gather_dimension() != most_frequent_dim) { const Shape& operand_shape = operand->shape(); // Build permutation to align gather dimension. auto& perm = operand_permutations.back(); perm = std::vector<int64_t>(operand_shape.rank()); std::iota(perm->begin(), perm->end(), 0); std::swap((*perm)[most_frequent_dim], (*perm)[ag->all_gather_dimension()]); // Bitcast operand and update output shape. operands.back() = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*perm, operand_shape), operand)); output_shapes.back() = ShapeUtil::PermuteDimensions(*perm, hlo->shape()); } } // Create combined all-gather op with a tuple result. HloInstruction* combined; combined = computation.AddInstruction(HloInstruction::CreateAllGather( ShapeUtil::MakeTupleShape(output_shapes), operands, most_frequent_dim, to_combine.front()->device_list(), /*constrain_layout=*/false, to_combine.front()->channel_id(), Cast<HloAllGatherInstruction>(to_combine.front()) ->use_global_device_ids())); // We have to propagate the sharding manually because Domain instructions are // not guaranteed to preserve it for side effecting instructions. combined->set_sharding( hlo_sharding_util::CreateTupleSharding(combined->shape(), to_combine)); VLOG(1) << "Replacing with : " << combined->ToString(); // Replace all the smaller all-gather ops with (bitcast) elements of the tuple // result. for (int64_t i = 0; i < to_combine.size(); ++i) { HloInstruction* replacement = computation.AddInstruction( HloInstruction::CreateGetTupleElement(combined, i)); if (operand_permutations[i]) { replacement = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*operand_permutations[i], replacement->shape()), replacement)); } TF_RETURN_IF_ERROR( computation.ReplaceInstruction(to_combine[i], replacement)); } return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; VLOG(1) << "Combining set"; VLOG(1) << "Set element: " << hlo->ToString(); VLOG(1) << "Replacing with : " << combined->ToString(); std::optional<GroupKey> CombineKey(const HloInstruction* instruction, const HloDomainMap& domain_map, bool combine_by_dim) { if (instruction->opcode() != HloOpcode::kAllGather) { return std::nullopt; } std::vector<std::vector<int64_t>> replica_groups; const auto* ag = Cast<HloAllGatherInstruction>(instruction); replica_groups.reserve(ag->replica_groups().size()); for (const ReplicaGroup& replica_group : ag->replica_groups()) { replica_groups.push_back( std::vector<int64_t>(replica_group.replica_ids().begin(), replica_group.replica_ids().end())); } // Ignore dimension (set to -1) if we are not grouping by dimension. int64_t ag_dim_key = combine_by_dim ? ag->all_gather_dimension() : -1; return GroupKey{ag_dim_key, domain_map.GetDomainMetadataId(ag), ag->channel_id().has_value(), ag->use_global_device_ids(), replica_groups}; } AllGatherCombiner::AllGatherCombiner(int64_t combine_threshold_in_bytes, int64_t combine_threshold_count, bool combine_by_dim) : combine_threshold_in_bytes_(combine_threshold_in_bytes), combine_threshold_count_(combine_threshold_count), combine_by_dim_(combine_by_dim) {} absl::StatusOr<bool> AllGatherCombiner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { VLOG(1) << "Running AllGatherCombiner with threshold of " << combine_threshold_in_bytes_ << " bytes"; if (combine_threshold_in_bytes_ <= 0 || combine_threshold_count_ <= 0) { VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; return false; } if (hlo_query::ContainsLayoutConstrainedCollective(*module, HloOpcode::kAllGather)) { VLOG(1) << "Skip AllGatherCombiner because the module contains " "all-gather with constrained layouts"; return false; } bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, "")); auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); }; auto combine_fn = [&](absl::Span<HloInstruction* const> to_combine) -> absl::Status { return CombineAllGathers(to_combine, combine_by_dim_); }; TF_ASSIGN_OR_RETURN( bool computation_changed, CombineInstructionsByKey<GroupKey>(computation, key_fn, combine_fn, combine_threshold_in_bytes_, combine_threshold_count_)); changed |= computation_changed; } return changed; } VLOG(1) << "Running AllGatherCombiner with threshold of " VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; VLOG(1) << "Skip AllGatherCombiner because the module contains " auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); };
#include "xla/service/all_gather_combiner.h" #include <cstdint> #include <memory> #include <vector> #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" TEST_F(AllGatherCombinerTest, CombineUpToThreshold) { const char* const hlo_string = R"( HloModule Module ENTRY entry { param0 = f32[8] parameter(0) param1 = f32[8] parameter(1) allgather0 = f32[32] all-gather(param0), replica_groups={}, dimensions={0} allgather1 = f32[32] all-gather(param1), replica_groups={}, dimensions={0} ROOT tuple = (f32[32], f32[32]) tuple(allgather0, allgather1) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(hlo_string)); // Run the AllGather combiner optimization pass with a threshold just higher // than that required such that the combination can occur. AllGatherCombiner combine(256, kMaxCombineCount, /*combine_by_dim=*/true); ASSERT_EQ(AllGatherCount(*module), 2); TF_ASSERT_OK_AND_ASSIGN(bool changed, combine.Run(module.get())); EXPECT_EQ(AllGatherCount(*module), 1); EXPECT_TRUE(changed); }
AllGatherCombinerTest_DomainPreventsCombining
xla/service/all_gather_combiner_test.cc
int64_t FindMostFrequentGatherDim( absl::Span<HloInstruction* const> to_combine) { assert(!to_combine.empty()); // Count frequencies. int64_t min_rank = std::numeric_limits<int64_t>::max(); std::vector<int64_t> frequency; for (const HloInstruction* it : to_combine) { int64_t dim = Cast<HloAllGatherInstruction>(it)->all_gather_dimension(); frequency.resize(std::max(dim + 1, static_cast<int64_t>(frequency.size())), 0); frequency[dim]++; min_rank = std::min(min_rank, it->shape().rank()); } int64_t most_frequent_dim = std::distance( frequency.begin(), std::max_element(frequency.begin(), frequency.end())); return most_frequent_dim < min_rank ? most_frequent_dim : 0; } absl::Status CombineAllGathers(absl::Span<HloInstruction* const> to_combine, bool combine_by_dim) { if (to_combine.size() < 2) { return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; HloComputation& computation = *to_combine.back()->parent(); // Create a single bigger AllGather of the operands of the smaller AllGather. std::vector<HloInstruction*> operands; std::vector<std::optional<std::vector<int64_t>>> operand_permutations; std::vector<Shape> output_shapes; // Find the most frequent all-gather dimension. int64_t most_frequent_dim = FindMostFrequentGatherDim(to_combine); VLOG(1) << "Combining set"; for (HloInstruction* hlo : to_combine) { VLOG(1) << "Set element: " << hlo->ToString(); TF_RET_CHECK(hlo->opcode() == HloOpcode::kAllGather); const auto* ag = Cast<HloAllGatherInstruction>(hlo); TF_RET_CHECK(hlo->operand_count() == 1); TF_RET_CHECK(hlo->shape().IsArray()); TF_RET_CHECK(!combine_by_dim || ag->all_gather_dimension() == most_frequent_dim); HloInstruction* operand = hlo->operands().front(); operands.push_back(operand); operand_permutations.emplace_back(); output_shapes.push_back(hlo->shape()); // Bitcast operand if needed. if (ag->all_gather_dimension() != most_frequent_dim) { const Shape& operand_shape = operand->shape(); // Build permutation to align gather dimension. auto& perm = operand_permutations.back(); perm = std::vector<int64_t>(operand_shape.rank()); std::iota(perm->begin(), perm->end(), 0); std::swap((*perm)[most_frequent_dim], (*perm)[ag->all_gather_dimension()]); // Bitcast operand and update output shape. operands.back() = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*perm, operand_shape), operand)); output_shapes.back() = ShapeUtil::PermuteDimensions(*perm, hlo->shape()); } } // Create combined all-gather op with a tuple result. HloInstruction* combined; combined = computation.AddInstruction(HloInstruction::CreateAllGather( ShapeUtil::MakeTupleShape(output_shapes), operands, most_frequent_dim, to_combine.front()->device_list(), /*constrain_layout=*/false, to_combine.front()->channel_id(), Cast<HloAllGatherInstruction>(to_combine.front()) ->use_global_device_ids())); // We have to propagate the sharding manually because Domain instructions are // not guaranteed to preserve it for side effecting instructions. combined->set_sharding( hlo_sharding_util::CreateTupleSharding(combined->shape(), to_combine)); VLOG(1) << "Replacing with : " << combined->ToString(); // Replace all the smaller all-gather ops with (bitcast) elements of the tuple // result. for (int64_t i = 0; i < to_combine.size(); ++i) { HloInstruction* replacement = computation.AddInstruction( HloInstruction::CreateGetTupleElement(combined, i)); if (operand_permutations[i]) { replacement = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*operand_permutations[i], replacement->shape()), replacement)); } TF_RETURN_IF_ERROR( computation.ReplaceInstruction(to_combine[i], replacement)); } return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; VLOG(1) << "Combining set"; VLOG(1) << "Set element: " << hlo->ToString(); VLOG(1) << "Replacing with : " << combined->ToString(); std::optional<GroupKey> CombineKey(const HloInstruction* instruction, const HloDomainMap& domain_map, bool combine_by_dim) { if (instruction->opcode() != HloOpcode::kAllGather) { return std::nullopt; } std::vector<std::vector<int64_t>> replica_groups; const auto* ag = Cast<HloAllGatherInstruction>(instruction); replica_groups.reserve(ag->replica_groups().size()); for (const ReplicaGroup& replica_group : ag->replica_groups()) { replica_groups.push_back( std::vector<int64_t>(replica_group.replica_ids().begin(), replica_group.replica_ids().end())); } // Ignore dimension (set to -1) if we are not grouping by dimension. int64_t ag_dim_key = combine_by_dim ? ag->all_gather_dimension() : -1; return GroupKey{ag_dim_key, domain_map.GetDomainMetadataId(ag), ag->channel_id().has_value(), ag->use_global_device_ids(), replica_groups}; } AllGatherCombiner::AllGatherCombiner(int64_t combine_threshold_in_bytes, int64_t combine_threshold_count, bool combine_by_dim) : combine_threshold_in_bytes_(combine_threshold_in_bytes), combine_threshold_count_(combine_threshold_count), combine_by_dim_(combine_by_dim) {} absl::StatusOr<bool> AllGatherCombiner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { VLOG(1) << "Running AllGatherCombiner with threshold of " << combine_threshold_in_bytes_ << " bytes"; if (combine_threshold_in_bytes_ <= 0 || combine_threshold_count_ <= 0) { VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; return false; } if (hlo_query::ContainsLayoutConstrainedCollective(*module, HloOpcode::kAllGather)) { VLOG(1) << "Skip AllGatherCombiner because the module contains " "all-gather with constrained layouts"; return false; } bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, "")); auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); }; auto combine_fn = [&](absl::Span<HloInstruction* const> to_combine) -> absl::Status { return CombineAllGathers(to_combine, combine_by_dim_); }; TF_ASSIGN_OR_RETURN( bool computation_changed, CombineInstructionsByKey<GroupKey>(computation, key_fn, combine_fn, combine_threshold_in_bytes_, combine_threshold_count_)); changed |= computation_changed; } return changed; } VLOG(1) << "Running AllGatherCombiner with threshold of " VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; VLOG(1) << "Skip AllGatherCombiner because the module contains " auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); };
#include "xla/service/all_gather_combiner.h" #include <cstdint> #include <memory> #include <vector> #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h"
AllGatherCombinerTest_DoNotCombineOverThreshold
xla/service/all_gather_combiner_test.cc
int64_t FindMostFrequentGatherDim( absl::Span<HloInstruction* const> to_combine) { assert(!to_combine.empty()); // Count frequencies. int64_t min_rank = std::numeric_limits<int64_t>::max(); std::vector<int64_t> frequency; for (const HloInstruction* it : to_combine) { int64_t dim = Cast<HloAllGatherInstruction>(it)->all_gather_dimension(); frequency.resize(std::max(dim + 1, static_cast<int64_t>(frequency.size())), 0); frequency[dim]++; min_rank = std::min(min_rank, it->shape().rank()); } int64_t most_frequent_dim = std::distance( frequency.begin(), std::max_element(frequency.begin(), frequency.end())); return most_frequent_dim < min_rank ? most_frequent_dim : 0; } absl::Status CombineAllGathers(absl::Span<HloInstruction* const> to_combine, bool combine_by_dim) { if (to_combine.size() < 2) { return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; HloComputation& computation = *to_combine.back()->parent(); // Create a single bigger AllGather of the operands of the smaller AllGather. std::vector<HloInstruction*> operands; std::vector<std::optional<std::vector<int64_t>>> operand_permutations; std::vector<Shape> output_shapes; // Find the most frequent all-gather dimension. int64_t most_frequent_dim = FindMostFrequentGatherDim(to_combine); VLOG(1) << "Combining set"; for (HloInstruction* hlo : to_combine) { VLOG(1) << "Set element: " << hlo->ToString(); TF_RET_CHECK(hlo->opcode() == HloOpcode::kAllGather); const auto* ag = Cast<HloAllGatherInstruction>(hlo); TF_RET_CHECK(hlo->operand_count() == 1); TF_RET_CHECK(hlo->shape().IsArray()); TF_RET_CHECK(!combine_by_dim || ag->all_gather_dimension() == most_frequent_dim); HloInstruction* operand = hlo->operands().front(); operands.push_back(operand); operand_permutations.emplace_back(); output_shapes.push_back(hlo->shape()); // Bitcast operand if needed. if (ag->all_gather_dimension() != most_frequent_dim) { const Shape& operand_shape = operand->shape(); // Build permutation to align gather dimension. auto& perm = operand_permutations.back(); perm = std::vector<int64_t>(operand_shape.rank()); std::iota(perm->begin(), perm->end(), 0); std::swap((*perm)[most_frequent_dim], (*perm)[ag->all_gather_dimension()]); // Bitcast operand and update output shape. operands.back() = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*perm, operand_shape), operand)); output_shapes.back() = ShapeUtil::PermuteDimensions(*perm, hlo->shape()); } } // Create combined all-gather op with a tuple result. HloInstruction* combined; combined = computation.AddInstruction(HloInstruction::CreateAllGather( ShapeUtil::MakeTupleShape(output_shapes), operands, most_frequent_dim, to_combine.front()->device_list(), /*constrain_layout=*/false, to_combine.front()->channel_id(), Cast<HloAllGatherInstruction>(to_combine.front()) ->use_global_device_ids())); // We have to propagate the sharding manually because Domain instructions are // not guaranteed to preserve it for side effecting instructions. combined->set_sharding( hlo_sharding_util::CreateTupleSharding(combined->shape(), to_combine)); VLOG(1) << "Replacing with : " << combined->ToString(); // Replace all the smaller all-gather ops with (bitcast) elements of the tuple // result. for (int64_t i = 0; i < to_combine.size(); ++i) { HloInstruction* replacement = computation.AddInstruction( HloInstruction::CreateGetTupleElement(combined, i)); if (operand_permutations[i]) { replacement = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*operand_permutations[i], replacement->shape()), replacement)); } TF_RETURN_IF_ERROR( computation.ReplaceInstruction(to_combine[i], replacement)); } return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; VLOG(1) << "Combining set"; VLOG(1) << "Set element: " << hlo->ToString(); VLOG(1) << "Replacing with : " << combined->ToString(); std::optional<GroupKey> CombineKey(const HloInstruction* instruction, const HloDomainMap& domain_map, bool combine_by_dim) { if (instruction->opcode() != HloOpcode::kAllGather) { return std::nullopt; } std::vector<std::vector<int64_t>> replica_groups; const auto* ag = Cast<HloAllGatherInstruction>(instruction); replica_groups.reserve(ag->replica_groups().size()); for (const ReplicaGroup& replica_group : ag->replica_groups()) { replica_groups.push_back( std::vector<int64_t>(replica_group.replica_ids().begin(), replica_group.replica_ids().end())); } // Ignore dimension (set to -1) if we are not grouping by dimension. int64_t ag_dim_key = combine_by_dim ? ag->all_gather_dimension() : -1; return GroupKey{ag_dim_key, domain_map.GetDomainMetadataId(ag), ag->channel_id().has_value(), ag->use_global_device_ids(), replica_groups}; } AllGatherCombiner::AllGatherCombiner(int64_t combine_threshold_in_bytes, int64_t combine_threshold_count, bool combine_by_dim) : combine_threshold_in_bytes_(combine_threshold_in_bytes), combine_threshold_count_(combine_threshold_count), combine_by_dim_(combine_by_dim) {} absl::StatusOr<bool> AllGatherCombiner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { VLOG(1) << "Running AllGatherCombiner with threshold of " << combine_threshold_in_bytes_ << " bytes"; if (combine_threshold_in_bytes_ <= 0 || combine_threshold_count_ <= 0) { VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; return false; } if (hlo_query::ContainsLayoutConstrainedCollective(*module, HloOpcode::kAllGather)) { VLOG(1) << "Skip AllGatherCombiner because the module contains " "all-gather with constrained layouts"; return false; } bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, "")); auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); }; auto combine_fn = [&](absl::Span<HloInstruction* const> to_combine) -> absl::Status { return CombineAllGathers(to_combine, combine_by_dim_); }; TF_ASSIGN_OR_RETURN( bool computation_changed, CombineInstructionsByKey<GroupKey>(computation, key_fn, combine_fn, combine_threshold_in_bytes_, combine_threshold_count_)); changed |= computation_changed; } return changed; } VLOG(1) << "Running AllGatherCombiner with threshold of " VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; VLOG(1) << "Skip AllGatherCombiner because the module contains " auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); };
#include "xla/service/all_gather_combiner.h" #include <cstdint> #include <memory> #include <vector> #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" TEST_F(AllGatherCombinerTest, DoNotCombineOverThreshold) { const char* const hlo_string = R"( HloModule Module ENTRY entry { param0 = f32[8] parameter(0) param1 = f32[8] parameter(1) allgather0 = f32[32] all-gather(param0), replica_groups={}, dimensions={0} allgather1 = f32[32] all-gather(param1), replica_groups={}, dimensions={0} ROOT tuple = (f32[32], f32[32]) tuple(allgather0, allgather1) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(hlo_string)); // Run the AllGather combiner optimization pass with threshold less than // the combined size of the all gather ops so that the combination // cannot occur. AllGatherCombiner combine(255, kMaxCombineCount, /*combine_by_dim=*/true); ASSERT_EQ(AllGatherCount(*module), 2); TF_ASSERT_OK_AND_ASSIGN(bool changed, combine.Run(module.get())); EXPECT_EQ(AllGatherCount(*module), 2); EXPECT_FALSE(changed); }
AllGatherCombinerTest_NoDependentCombination
xla/service/all_gather_combiner_test.cc
int64_t FindMostFrequentGatherDim( absl::Span<HloInstruction* const> to_combine) { assert(!to_combine.empty()); // Count frequencies. int64_t min_rank = std::numeric_limits<int64_t>::max(); std::vector<int64_t> frequency; for (const HloInstruction* it : to_combine) { int64_t dim = Cast<HloAllGatherInstruction>(it)->all_gather_dimension(); frequency.resize(std::max(dim + 1, static_cast<int64_t>(frequency.size())), 0); frequency[dim]++; min_rank = std::min(min_rank, it->shape().rank()); } int64_t most_frequent_dim = std::distance( frequency.begin(), std::max_element(frequency.begin(), frequency.end())); return most_frequent_dim < min_rank ? most_frequent_dim : 0; } absl::Status CombineAllGathers(absl::Span<HloInstruction* const> to_combine, bool combine_by_dim) { if (to_combine.size() < 2) { return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; HloComputation& computation = *to_combine.back()->parent(); // Create a single bigger AllGather of the operands of the smaller AllGather. std::vector<HloInstruction*> operands; std::vector<std::optional<std::vector<int64_t>>> operand_permutations; std::vector<Shape> output_shapes; // Find the most frequent all-gather dimension. int64_t most_frequent_dim = FindMostFrequentGatherDim(to_combine); VLOG(1) << "Combining set"; for (HloInstruction* hlo : to_combine) { VLOG(1) << "Set element: " << hlo->ToString(); TF_RET_CHECK(hlo->opcode() == HloOpcode::kAllGather); const auto* ag = Cast<HloAllGatherInstruction>(hlo); TF_RET_CHECK(hlo->operand_count() == 1); TF_RET_CHECK(hlo->shape().IsArray()); TF_RET_CHECK(!combine_by_dim || ag->all_gather_dimension() == most_frequent_dim); HloInstruction* operand = hlo->operands().front(); operands.push_back(operand); operand_permutations.emplace_back(); output_shapes.push_back(hlo->shape()); // Bitcast operand if needed. if (ag->all_gather_dimension() != most_frequent_dim) { const Shape& operand_shape = operand->shape(); // Build permutation to align gather dimension. auto& perm = operand_permutations.back(); perm = std::vector<int64_t>(operand_shape.rank()); std::iota(perm->begin(), perm->end(), 0); std::swap((*perm)[most_frequent_dim], (*perm)[ag->all_gather_dimension()]); // Bitcast operand and update output shape. operands.back() = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*perm, operand_shape), operand)); output_shapes.back() = ShapeUtil::PermuteDimensions(*perm, hlo->shape()); } } // Create combined all-gather op with a tuple result. HloInstruction* combined; combined = computation.AddInstruction(HloInstruction::CreateAllGather( ShapeUtil::MakeTupleShape(output_shapes), operands, most_frequent_dim, to_combine.front()->device_list(), /*constrain_layout=*/false, to_combine.front()->channel_id(), Cast<HloAllGatherInstruction>(to_combine.front()) ->use_global_device_ids())); // We have to propagate the sharding manually because Domain instructions are // not guaranteed to preserve it for side effecting instructions. combined->set_sharding( hlo_sharding_util::CreateTupleSharding(combined->shape(), to_combine)); VLOG(1) << "Replacing with : " << combined->ToString(); // Replace all the smaller all-gather ops with (bitcast) elements of the tuple // result. for (int64_t i = 0; i < to_combine.size(); ++i) { HloInstruction* replacement = computation.AddInstruction( HloInstruction::CreateGetTupleElement(combined, i)); if (operand_permutations[i]) { replacement = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*operand_permutations[i], replacement->shape()), replacement)); } TF_RETURN_IF_ERROR( computation.ReplaceInstruction(to_combine[i], replacement)); } return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; VLOG(1) << "Combining set"; VLOG(1) << "Set element: " << hlo->ToString(); VLOG(1) << "Replacing with : " << combined->ToString(); std::optional<GroupKey> CombineKey(const HloInstruction* instruction, const HloDomainMap& domain_map, bool combine_by_dim) { if (instruction->opcode() != HloOpcode::kAllGather) { return std::nullopt; } std::vector<std::vector<int64_t>> replica_groups; const auto* ag = Cast<HloAllGatherInstruction>(instruction); replica_groups.reserve(ag->replica_groups().size()); for (const ReplicaGroup& replica_group : ag->replica_groups()) { replica_groups.push_back( std::vector<int64_t>(replica_group.replica_ids().begin(), replica_group.replica_ids().end())); } // Ignore dimension (set to -1) if we are not grouping by dimension. int64_t ag_dim_key = combine_by_dim ? ag->all_gather_dimension() : -1; return GroupKey{ag_dim_key, domain_map.GetDomainMetadataId(ag), ag->channel_id().has_value(), ag->use_global_device_ids(), replica_groups}; } AllGatherCombiner::AllGatherCombiner(int64_t combine_threshold_in_bytes, int64_t combine_threshold_count, bool combine_by_dim) : combine_threshold_in_bytes_(combine_threshold_in_bytes), combine_threshold_count_(combine_threshold_count), combine_by_dim_(combine_by_dim) {} absl::StatusOr<bool> AllGatherCombiner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { VLOG(1) << "Running AllGatherCombiner with threshold of " << combine_threshold_in_bytes_ << " bytes"; if (combine_threshold_in_bytes_ <= 0 || combine_threshold_count_ <= 0) { VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; return false; } if (hlo_query::ContainsLayoutConstrainedCollective(*module, HloOpcode::kAllGather)) { VLOG(1) << "Skip AllGatherCombiner because the module contains " "all-gather with constrained layouts"; return false; } bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, "")); auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); }; auto combine_fn = [&](absl::Span<HloInstruction* const> to_combine) -> absl::Status { return CombineAllGathers(to_combine, combine_by_dim_); }; TF_ASSIGN_OR_RETURN( bool computation_changed, CombineInstructionsByKey<GroupKey>(computation, key_fn, combine_fn, combine_threshold_in_bytes_, combine_threshold_count_)); changed |= computation_changed; } return changed; } VLOG(1) << "Running AllGatherCombiner with threshold of " VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; VLOG(1) << "Skip AllGatherCombiner because the module contains " auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); };
#include "xla/service/all_gather_combiner.h" #include <cstdint> #include <memory> #include <vector> #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" TEST_F(AllGatherCombinerTest, NoDependentCombination) { const char* const hlo_string = R"( HloModule Module ENTRY entry { param = f32[1] parameter(0) allgather0 = f32[2] all-gather(param), replica_groups={}, dimensions={0} ROOT allgather1 = f32[4] all-gather(allgather0), replica_groups={}, dimensions={0} } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(hlo_string)); AllGatherCombiner combine(1024 * 1024, kMaxCombineCount, /*combine_by_dim=*/true); ASSERT_EQ(AllGatherCount(*module), 2); TF_ASSERT_OK_AND_ASSIGN(bool changed, combine.Run(module.get())); EXPECT_EQ(AllGatherCount(*module), 2); EXPECT_FALSE(changed); }
AllGatherCombinerTest_NoDifferentReplicaGroupsCombination
xla/service/all_gather_combiner_test.cc
int64_t FindMostFrequentGatherDim( absl::Span<HloInstruction* const> to_combine) { assert(!to_combine.empty()); // Count frequencies. int64_t min_rank = std::numeric_limits<int64_t>::max(); std::vector<int64_t> frequency; for (const HloInstruction* it : to_combine) { int64_t dim = Cast<HloAllGatherInstruction>(it)->all_gather_dimension(); frequency.resize(std::max(dim + 1, static_cast<int64_t>(frequency.size())), 0); frequency[dim]++; min_rank = std::min(min_rank, it->shape().rank()); } int64_t most_frequent_dim = std::distance( frequency.begin(), std::max_element(frequency.begin(), frequency.end())); return most_frequent_dim < min_rank ? most_frequent_dim : 0; } absl::Status CombineAllGathers(absl::Span<HloInstruction* const> to_combine, bool combine_by_dim) { if (to_combine.size() < 2) { return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; HloComputation& computation = *to_combine.back()->parent(); // Create a single bigger AllGather of the operands of the smaller AllGather. std::vector<HloInstruction*> operands; std::vector<std::optional<std::vector<int64_t>>> operand_permutations; std::vector<Shape> output_shapes; // Find the most frequent all-gather dimension. int64_t most_frequent_dim = FindMostFrequentGatherDim(to_combine); VLOG(1) << "Combining set"; for (HloInstruction* hlo : to_combine) { VLOG(1) << "Set element: " << hlo->ToString(); TF_RET_CHECK(hlo->opcode() == HloOpcode::kAllGather); const auto* ag = Cast<HloAllGatherInstruction>(hlo); TF_RET_CHECK(hlo->operand_count() == 1); TF_RET_CHECK(hlo->shape().IsArray()); TF_RET_CHECK(!combine_by_dim || ag->all_gather_dimension() == most_frequent_dim); HloInstruction* operand = hlo->operands().front(); operands.push_back(operand); operand_permutations.emplace_back(); output_shapes.push_back(hlo->shape()); // Bitcast operand if needed. if (ag->all_gather_dimension() != most_frequent_dim) { const Shape& operand_shape = operand->shape(); // Build permutation to align gather dimension. auto& perm = operand_permutations.back(); perm = std::vector<int64_t>(operand_shape.rank()); std::iota(perm->begin(), perm->end(), 0); std::swap((*perm)[most_frequent_dim], (*perm)[ag->all_gather_dimension()]); // Bitcast operand and update output shape. operands.back() = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*perm, operand_shape), operand)); output_shapes.back() = ShapeUtil::PermuteDimensions(*perm, hlo->shape()); } } // Create combined all-gather op with a tuple result. HloInstruction* combined; combined = computation.AddInstruction(HloInstruction::CreateAllGather( ShapeUtil::MakeTupleShape(output_shapes), operands, most_frequent_dim, to_combine.front()->device_list(), /*constrain_layout=*/false, to_combine.front()->channel_id(), Cast<HloAllGatherInstruction>(to_combine.front()) ->use_global_device_ids())); // We have to propagate the sharding manually because Domain instructions are // not guaranteed to preserve it for side effecting instructions. combined->set_sharding( hlo_sharding_util::CreateTupleSharding(combined->shape(), to_combine)); VLOG(1) << "Replacing with : " << combined->ToString(); // Replace all the smaller all-gather ops with (bitcast) elements of the tuple // result. for (int64_t i = 0; i < to_combine.size(); ++i) { HloInstruction* replacement = computation.AddInstruction( HloInstruction::CreateGetTupleElement(combined, i)); if (operand_permutations[i]) { replacement = computation.AddInstruction(HloInstruction::CreateBitcast( ShapeUtil::PermuteDimensions(*operand_permutations[i], replacement->shape()), replacement)); } TF_RETURN_IF_ERROR( computation.ReplaceInstruction(to_combine[i], replacement)); } return absl::OkStatus(); } VLOG(1) << "Combined " << to_combine.size() << " AllGather ops"; VLOG(1) << "Combining set"; VLOG(1) << "Set element: " << hlo->ToString(); VLOG(1) << "Replacing with : " << combined->ToString(); std::optional<GroupKey> CombineKey(const HloInstruction* instruction, const HloDomainMap& domain_map, bool combine_by_dim) { if (instruction->opcode() != HloOpcode::kAllGather) { return std::nullopt; } std::vector<std::vector<int64_t>> replica_groups; const auto* ag = Cast<HloAllGatherInstruction>(instruction); replica_groups.reserve(ag->replica_groups().size()); for (const ReplicaGroup& replica_group : ag->replica_groups()) { replica_groups.push_back( std::vector<int64_t>(replica_group.replica_ids().begin(), replica_group.replica_ids().end())); } // Ignore dimension (set to -1) if we are not grouping by dimension. int64_t ag_dim_key = combine_by_dim ? ag->all_gather_dimension() : -1; return GroupKey{ag_dim_key, domain_map.GetDomainMetadataId(ag), ag->channel_id().has_value(), ag->use_global_device_ids(), replica_groups}; } AllGatherCombiner::AllGatherCombiner(int64_t combine_threshold_in_bytes, int64_t combine_threshold_count, bool combine_by_dim) : combine_threshold_in_bytes_(combine_threshold_in_bytes), combine_threshold_count_(combine_threshold_count), combine_by_dim_(combine_by_dim) {} absl::StatusOr<bool> AllGatherCombiner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { VLOG(1) << "Running AllGatherCombiner with threshold of " << combine_threshold_in_bytes_ << " bytes"; if (combine_threshold_in_bytes_ <= 0 || combine_threshold_count_ <= 0) { VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; return false; } if (hlo_query::ContainsLayoutConstrainedCollective(*module, HloOpcode::kAllGather)) { VLOG(1) << "Skip AllGatherCombiner because the module contains " "all-gather with constrained layouts"; return false; } bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, "")); auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); }; auto combine_fn = [&](absl::Span<HloInstruction* const> to_combine) -> absl::Status { return CombineAllGathers(to_combine, combine_by_dim_); }; TF_ASSIGN_OR_RETURN( bool computation_changed, CombineInstructionsByKey<GroupKey>(computation, key_fn, combine_fn, combine_threshold_in_bytes_, combine_threshold_count_)); changed |= computation_changed; } return changed; } VLOG(1) << "Running AllGatherCombiner with threshold of " VLOG(1) << "Skip AllGatherCombiner because the threshold is zero"; VLOG(1) << "Skip AllGatherCombiner because the module contains " auto key_fn = [&](const HloInstruction* instruction) { return CombineKey(instruction, *domain_map, combine_by_dim_); };
#include "xla/service/all_gather_combiner.h" #include <cstdint> #include <memory> #include <vector> #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h"
CollectivePipelinerTest_ElementWiseUser
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, ElementWiseUser) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(3) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,8,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.5, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) ar.1 = bf16[1,8,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 mul2 = bf16[1,8,128] multiply(ar.1, mul) dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, mul2, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5) } ENTRY entry { c0 = s32[] constant(0) p0 = bf16[3,8,128] parameter(0) tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true, 0, /*pipeline_use_tree=*/true, /*process_different_sized_ops=*/true, CollectivePipeliner::PipeliningDirection::kForward) .value()); XLA_VLOG_LINES(1, module->ToString()); }
CollectivePipelinerTest_EscapedInputNoTransform
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, EscapedInputNoTransform) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[1,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(0) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[1,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,8,128] get-tuple-element(param), index=3 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.911 = bf16[1,8,128] dynamic-slice(get-tuple-element.395, constant.2561, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.395, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) ar.1 = bf16[1,8,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, ar.1, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[1,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, dynamic-slice.911, get-tuple-element.5) } ENTRY entry { c0 = s32[] constant(-3) p0 = bf16[3,8,128] parameter(0) cc = bf16[] constant(0) c1 = bf16[1,8,128] broadcast(cc), dimensions={} c2 = bf16[3,8,128] broadcast(cc), dimensions={} tuple = (s32[], bf16[3,8,128], bf16[1,8,128], bf16[3,8,128]) tuple(c0, p0, c1, c2) while = (s32[], bf16[3,8,128], bf16[1,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); XLA_VLOG_LINES(1, module->ToString()); EXPECT_FALSE(RunOptimizer(module.get(), /*last_run=*/true).value()); }
CollectivePipelinerTest_MultiUsesElementwise
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, MultiUsesElementwise) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(3) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,8,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.5, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) c2 = bf16[] constant(2.0) bc = bf16[1,8,128] broadcast(c2) ar.1 = bf16[1,8,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 mul2 = bf16[1,8,128] multiply(ar.1, bc) mul3 = bf16[1,8,128] multiply(mul2, ar.1) mul4 = bf16[1,8,128] multiply(mul3, mul) dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, mul4, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5) } ENTRY entry { c0 = s32[] constant(0) p0 = bf16[3,8,128] parameter(0) tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true, 0, /*pipeline_use_tree=*/true, /*process_different_sized_ops=*/true, CollectivePipeliner::PipeliningDirection::kForward) .value()); XLA_VLOG_LINES(1, module->ToString()); }
CollectivePipelinerTest_MultiUsesElementwiseFeedTwo
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, MultiUsesElementwiseFeedTwo) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(3) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,8,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.5, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) c2 = bf16[] constant(2.0) bc = bf16[1,8,128] broadcast(c2) ar.1 = bf16[1,8,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 ar.2 = bf16[1,8,128] all-reduce(ar.1), replica_groups={}, to_apply=add, channel_id=1 mul2 = bf16[1,8,128] multiply(ar.1, bc), control-predecessors={ar.1} mul3 = bf16[1,8,128] multiply(mul2, ar.2) mul4 = bf16[1,8,128] multiply(mul3, mul) dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, mul4, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5), control-predecessors={ar.1} } ENTRY entry { c0 = s32[] constant(0) p0 = bf16[3,8,128] parameter(0) tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true, 0, /*pipeline_use_tree=*/true, /*process_different_sized_ops=*/true, CollectivePipeliner::PipeliningDirection::kForward) .value()); XLA_VLOG_LINES(1, module->ToString()); }
CollectivePipelinerTest_MultiUsesElementwiseFeedTwoWithReduce
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, MultiUsesElementwiseFeedTwoWithReduce) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } add.1 { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } add.2 { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(3) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,8,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.5, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) bm = bf16[1,1,8,128] broadcast(mul), dimensions={1,2,3} c2 = bf16[] constant(2.0) bc = bf16[1,8,128] broadcast(c2) ar.1 = bf16[1,1,8,128] all-reduce(bm), replica_groups={}, to_apply=add, channel_id=1 ar.2 = bf16[1,1,8,128] all-reduce(ar.1), replica_groups={}, to_apply=add, channel_id=2 red.1 = bf16[1,8,128] reduce(ar.1, c2), to_apply=add.1, dimensions={0} red.2 = bf16[1,8,128] reduce(ar.2, c2), to_apply=add.2, dimensions={0} mul2 = bf16[1,8,128] multiply(red.1, bc), control-predecessors={ar.1} mul3 = bf16[1,8,128] multiply(mul2, red.2) mul4 = bf16[1,8,128] multiply(mul3, mul) dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, mul4, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5), control-predecessors={ar.1} } ENTRY entry { c0 = s32[] constant(0) p0 = bf16[3,8,128] parameter(0) tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true, 0, /*pipeline_use_tree=*/true, /*process_different_sized_ops=*/true, CollectivePipeliner::PipeliningDirection::kForward) .value()); XLA_VLOG_LINES(1, module->ToString()); }
CollectivePipelinerTest_MultiUsesElementwiseMerge
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, MultiUsesElementwiseMerge) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(3) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,8,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.5, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) c2 = bf16[] constant(2.0) bc = bf16[1,8,128] broadcast(c2) ar.1 = bf16[1,8,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 ar.2 = bf16[1,8,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 mul2 = bf16[1,8,128] multiply(ar.1, bc) mul3 = bf16[1,8,128] multiply(mul2, ar.2) mul4 = bf16[1,8,128] multiply(mul3, mul) dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, mul4, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5) } ENTRY entry { c0 = s32[] constant(0) p0 = bf16[3,8,128] parameter(0) tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true, 0, /*pipeline_use_tree=*/true, /*process_different_sized_ops=*/true, CollectivePipeliner::PipeliningDirection::kForward) .value()); XLA_VLOG_LINES(1, module->ToString()); }
CollectivePipelinerTest_NoPushAgOverBecauseDifferentSize
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, NoPushAgOverBecauseDifferentSize) { constexpr absl::string_view hlo_string = R"( HloModule module, entry_computation_layout={(bf16[3,8,128]{2,1,0})->bf16[3,8,128]{2,1,0}} %add (lhs: bf16[], rhs: bf16[]) -> bf16[] { %lhs = bf16[] parameter(0) %rhs = bf16[] parameter(1) ROOT %add = bf16[] add(bf16[] %lhs, bf16[] %rhs) } %while_body.clone (loop_peel_param: (s32[], bf16[3,8,128], s32[])) -> (s32[], bf16[3,8,128], s32[]) { %loop_peel_param = (s32[], bf16[3,8,128]{2,1,0}, s32[]) parameter(0) %get-tuple-element.2 = s32[] get-tuple-element((s32[], bf16[3,8,128]{2,1,0}, s32[]) %loop_peel_param), index=0 %constant.7 = s32[] constant(1) %add.4 = s32[] add(s32[] %get-tuple-element.2, s32[] %constant.7) %get-tuple-element.3 = bf16[3,8,128]{2,1,0} get-tuple-element((s32[], bf16[3,8,128]{2,1,0}, s32[]) %loop_peel_param), index=1 %get-tuple-element.4 = s32[] get-tuple-element((s32[], bf16[3,8,128]{2,1,0}, s32[]) %loop_peel_param), index=2 %constant.12 = s64[] constant(1) %custom-call = s32[] custom-call(s32[] %get-tuple-element.4, s64[] %constant.12), custom_call_target="InsertedByPreviousStep" %constant.13 = s32[] constant(0) %constant.10 = s32[] constant(0) %dynamic-slice.2 = bf16[1,8,128]{2,1,0} dynamic-slice(bf16[3,8,128]{2,1,0} %get-tuple-element.3, s32[] %custom-call, s32[] %constant.13, s32[] %constant.13), dynamic_slice_sizes={1,8,128} %ar.2 = bf16[1,1,128]{2,1,0} reduce-scatter(bf16[1,8,128]{2,1,0} %dynamic-slice.2), channel_id=2, replica_groups={}, to_apply=%add, dimensions={1} %ag.2 = bf16[1,8,128]{2,1,0} all-gather(bf16[1,1,128]{2,1,0} %ar.2), channel_id=32, replica_groups={}, dimensions={1} %dynamic-update-slice.2 = bf16[3,8,128]{2,1,0} dynamic-update-slice(bf16[3,8,128]{2,1,0} %get-tuple-element.3, bf16[1,8,128]{2,1,0} %ag.2, s32[] %custom-call, s32[] %constant.13, s32[] %constant.13) %dynamic-slice.1 = bf16[1,8,128]{2,1,0} dynamic-slice(bf16[3,8,128]{2,1,0} %get-tuple-element.3, s32[] %get-tuple-element.2, s32[] %constant.10, s32[] %constant.10), dynamic_slice_sizes={1,8,128} %mul.2 = bf16[1,8,128]{2,1,0} multiply(bf16[1,8,128]{2,1,0} %dynamic-slice.1, bf16[1,8,128]{2,1,0} %dynamic-slice.1) %constant.15 = s32[] constant(0) %dynamic-update-slice.4 = bf16[3,8,128]{2,1,0} dynamic-update-slice(bf16[3,8,128]{2,1,0} %dynamic-update-slice.2, bf16[1,8,128]{2,1,0} %mul.2, s32[] %get-tuple-element.2, s32[] %constant.15, s32[] %constant.15) ROOT %tuple.3 = (s32[], bf16[3,8,128]{2,1,0}, s32[]) tuple(s32[] %add.4, bf16[3,8,128]{2,1,0} %dynamic-update-slice.4, s32[] %get-tuple-element.2) } %while_cond.clone (loop_peel_cond_param: (s32[], bf16[3,8,128], s32[])) -> pred[] { %loop_peel_cond_param = (s32[], bf16[3,8,128]{2,1,0}, s32[]) parameter(0) %gte.1 = s32[] get-tuple-element((s32[], bf16[3,8,128]{2,1,0}, s32[]) %loop_peel_cond_param), index=0 %constant.6 = s32[] constant(0) ROOT %cmp.1 = pred[] compare(s32[] %gte.1, s32[] %constant.6), direction=LT } ENTRY %entry (p0: bf16[3,8,128]) -> bf16[3,8,128] { %c0 = s32[] constant(-3) %p0 = bf16[3,8,128]{2,1,0} parameter(0) %tuple.1 = (s32[], bf16[3,8,128]{2,1,0}) tuple(s32[] %c0, bf16[3,8,128]{2,1,0} %p0) %get-tuple-element.0 = s32[] get-tuple-element((s32[], bf16[3,8,128]{2,1,0}) %tuple.1), index=0 %constant.0 = s32[] constant(1) %constant.4 = s32[] constant(0) %add.1 = s32[] add(s32[] %get-tuple-element.0, s32[] %constant.0) %get-tuple-element.1 = bf16[3,8,128]{2,1,0} get-tuple-element((s32[], bf16[3,8,128]{2,1,0}) %tuple.1), index=1 %dynamic-slice.0 = bf16[1,8,128]{2,1,0} dynamic-slice(bf16[3,8,128]{2,1,0} %get-tuple-element.1, s32[] %get-tuple-element.0, s32[] %constant.4, s32[] %constant.4), dynamic_slice_sizes={1,8,128} %mul.1 = bf16[1,8,128]{2,1,0} multiply(bf16[1,8,128]{2,1,0} %dynamic-slice.0, bf16[1,8,128]{2,1,0} %dynamic-slice.0) %dynamic-update-slice.0 = bf16[3,8,128]{2,1,0} dynamic-update-slice(bf16[3,8,128]{2,1,0} %get-tuple-element.1, bf16[1,8,128]{2,1,0} %mul.1, s32[] %get-tuple-element.0, s32[] %constant.4, s32[] %constant.4) %tuple.4 = (s32[], bf16[3,8,128]{2,1,0}, s32[]) tuple(s32[] %add.1, bf16[3,8,128]{2,1,0} %dynamic-update-slice.0, s32[] %get-tuple-element.0) %while.1 = (s32[], bf16[3,8,128]{2,1,0}, s32[]) while((s32[], bf16[3,8,128]{2,1,0}, s32[]) %tuple.4), condition=%while_cond.clone, body=%while_body.clone %get-tuple-element.6 = bf16[3,8,128]{2,1,0} get-tuple-element((s32[], bf16[3,8,128]{2,1,0}, s32[]) %while.1), index=1 %get-tuple-element.5 = s32[] get-tuple-element((s32[], bf16[3,8,128]{2,1,0}, s32[]) %while.1), index=2 %constant.14 = s32[] constant(0) %dynamic-slice.3 = bf16[1,8,128]{2,1,0} dynamic-slice(bf16[3,8,128]{2,1,0} %get-tuple-element.6, s32[] %get-tuple-element.5, s32[] %constant.14, s32[] %constant.14), dynamic_slice_sizes={1,8,128} %ar.3 = bf16[1,8,128]{2,1,0} all-reduce(bf16[1,8,128]{2,1,0} %dynamic-slice.3), channel_id=3, replica_groups={}, to_apply=%add ROOT %dynamic-update-slice.3 = bf16[3,8,128]{2,1,0} dynamic-update-slice(bf16[3,8,128]{2,1,0} %get-tuple-element.6, bf16[1,8,128]{2,1,0} %ar.3, s32[] %get-tuple-element.5, s32[] %constant.14, s32[] %constant.14) } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_FALSE(RunOptimizer(module.get(), /*last_run=*/false, 1, /*pipeline_use_tree=*/false, /*process_different_sized_ops=*/false, CollectivePipeliner::PipeliningDirection::kForward, IsAllGather) .value()); XLA_VLOG_LINES(1, module->ToString()); }
CollectivePipelinerTest_NoTransformCantProveIndexDoesntWrap
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, NoTransformCantProveIndexDoesntWrap) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(4) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,8,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.5, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) ar.1 = bf16[1,8,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, ar.1, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5) } ENTRY entry { c0 = s32[] constant(-1) p0 = bf16[3,8,128] parameter(0) tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_FALSE(RunOptimizer(module.get(), /*last_run=*/true).value()); XLA_VLOG_LINES(1, module->ToString()); }
CollectivePipelinerTest_NotTransformAllGatherWithRecvInChainBackwards
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; };
CollectivePipelinerTest_PipelinedReduceScatterCanPassVerifier
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; };
CollectivePipelinerTest_PushAgOver
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, PushAgOver) { constexpr absl::string_view hlo_string = R"( HloModule module, entry_computation_layout={(bf16[3,8,128]{2,1,0})->bf16[3,8,128]{2,1,0}} %add (lhs: bf16[], rhs: bf16[]) -> bf16[] { %lhs = bf16[] parameter(0) %rhs = bf16[] parameter(1) ROOT %add = bf16[] add(bf16[] %lhs, bf16[] %rhs) } %while_body.clone (loop_peel_param: (s32[], bf16[3,8,128], s32[])) -> (s32[], bf16[3,8,128], s32[]) { %loop_peel_param = (s32[], bf16[3,8,128]{2,1,0}, s32[]) parameter(0) %get-tuple-element.2 = s32[] get-tuple-element((s32[], bf16[3,8,128]{2,1,0}, s32[]) %loop_peel_param), index=0 %constant.7 = s32[] constant(1) %add.4 = s32[] add(s32[] %get-tuple-element.2, s32[] %constant.7) %get-tuple-element.3 = bf16[3,8,128]{2,1,0} get-tuple-element((s32[], bf16[3,8,128]{2,1,0}, s32[]) %loop_peel_param), index=1 %get-tuple-element.4 = s32[] get-tuple-element((s32[], bf16[3,8,128]{2,1,0}, s32[]) %loop_peel_param), index=2 %constant.12 = s64[] constant(1) %custom-call = s32[] custom-call(s32[] %get-tuple-element.4, s64[] %constant.12), custom_call_target="InsertedByPreviousStep" %constant.13 = s32[] constant(0) %constant.10 = s32[] constant(0) %dynamic-slice.2 = bf16[1,8,128]{2,1,0} dynamic-slice(bf16[3,8,128]{2,1,0} %get-tuple-element.3, s32[] %custom-call, s32[] %constant.13, s32[] %constant.13), dynamic_slice_sizes={1,8,128} %ar.2 = bf16[1,1,128]{2,1,0} reduce-scatter(bf16[1,8,128]{2,1,0} %dynamic-slice.2), channel_id=2, replica_groups={}, to_apply=%add, dimensions={1} %ag.2 = bf16[1,8,128]{2,1,0} all-gather(bf16[1,1,128]{2,1,0} %ar.2), channel_id=32, replica_groups={}, dimensions={1} %dynamic-update-slice.2 = bf16[3,8,128]{2,1,0} dynamic-update-slice(bf16[3,8,128]{2,1,0} %get-tuple-element.3, bf16[1,8,128]{2,1,0} %ag.2, s32[] %custom-call, s32[] %constant.13, s32[] %constant.13) %dynamic-slice.1 = bf16[1,8,128]{2,1,0} dynamic-slice(bf16[3,8,128]{2,1,0} %get-tuple-element.3, s32[] %get-tuple-element.2, s32[] %constant.10, s32[] %constant.10), dynamic_slice_sizes={1,8,128} %mul.2 = bf16[1,8,128]{2,1,0} multiply(bf16[1,8,128]{2,1,0} %dynamic-slice.1, bf16[1,8,128]{2,1,0} %dynamic-slice.1) %constant.15 = s32[] constant(0) %dynamic-update-slice.4 = bf16[3,8,128]{2,1,0} dynamic-update-slice(bf16[3,8,128]{2,1,0} %dynamic-update-slice.2, bf16[1,8,128]{2,1,0} %mul.2, s32[] %get-tuple-element.2, s32[] %constant.15, s32[] %constant.15) ROOT %tuple.3 = (s32[], bf16[3,8,128]{2,1,0}, s32[]) tuple(s32[] %add.4, bf16[3,8,128]{2,1,0} %dynamic-update-slice.4, s32[] %get-tuple-element.2) } %while_cond.clone (loop_peel_cond_param: (s32[], bf16[3,8,128], s32[])) -> pred[] { %loop_peel_cond_param = (s32[], bf16[3,8,128]{2,1,0}, s32[]) parameter(0) %gte.1 = s32[] get-tuple-element((s32[], bf16[3,8,128]{2,1,0}, s32[]) %loop_peel_cond_param), index=0 %constant.6 = s32[] constant(0) ROOT %cmp.1 = pred[] compare(s32[] %gte.1, s32[] %constant.6), direction=LT } ENTRY %entry (p0: bf16[3,8,128]) -> bf16[3,8,128] { %c0 = s32[] constant(-3) %p0 = bf16[3,8,128]{2,1,0} parameter(0) %tuple.1 = (s32[], bf16[3,8,128]{2,1,0}) tuple(s32[] %c0, bf16[3,8,128]{2,1,0} %p0) %get-tuple-element.0 = s32[] get-tuple-element((s32[], bf16[3,8,128]{2,1,0}) %tuple.1), index=0 %constant.0 = s32[] constant(1) %constant.4 = s32[] constant(0) %add.1 = s32[] add(s32[] %get-tuple-element.0, s32[] %constant.0) %get-tuple-element.1 = bf16[3,8,128]{2,1,0} get-tuple-element((s32[], bf16[3,8,128]{2,1,0}) %tuple.1), index=1 %dynamic-slice.0 = bf16[1,8,128]{2,1,0} dynamic-slice(bf16[3,8,128]{2,1,0} %get-tuple-element.1, s32[] %get-tuple-element.0, s32[] %constant.4, s32[] %constant.4), dynamic_slice_sizes={1,8,128} %mul.1 = bf16[1,8,128]{2,1,0} multiply(bf16[1,8,128]{2,1,0} %dynamic-slice.0, bf16[1,8,128]{2,1,0} %dynamic-slice.0) %dynamic-update-slice.0 = bf16[3,8,128]{2,1,0} dynamic-update-slice(bf16[3,8,128]{2,1,0} %get-tuple-element.1, bf16[1,8,128]{2,1,0} %mul.1, s32[] %get-tuple-element.0, s32[] %constant.4, s32[] %constant.4) %tuple.4 = (s32[], bf16[3,8,128]{2,1,0}, s32[]) tuple(s32[] %add.1, bf16[3,8,128]{2,1,0} %dynamic-update-slice.0, s32[] %get-tuple-element.0) %while.1 = (s32[], bf16[3,8,128]{2,1,0}, s32[]) while((s32[], bf16[3,8,128]{2,1,0}, s32[]) %tuple.4), condition=%while_cond.clone, body=%while_body.clone %get-tuple-element.6 = bf16[3,8,128]{2,1,0} get-tuple-element((s32[], bf16[3,8,128]{2,1,0}, s32[]) %while.1), index=1 %get-tuple-element.5 = s32[] get-tuple-element((s32[], bf16[3,8,128]{2,1,0}, s32[]) %while.1), index=2 %constant.14 = s32[] constant(0) %dynamic-slice.3 = bf16[1,8,128]{2,1,0} dynamic-slice(bf16[3,8,128]{2,1,0} %get-tuple-element.6, s32[] %get-tuple-element.5, s32[] %constant.14, s32[] %constant.14), dynamic_slice_sizes={1,8,128} %ar.3 = bf16[1,8,128]{2,1,0} all-reduce(bf16[1,8,128]{2,1,0} %dynamic-slice.3), channel_id=3, replica_groups={}, to_apply=%add ROOT %dynamic-update-slice.3 = bf16[3,8,128]{2,1,0} dynamic-update-slice(bf16[3,8,128]{2,1,0} %get-tuple-element.6, bf16[1,8,128]{2,1,0} %ar.3, s32[] %get-tuple-element.5, s32[] %constant.14, s32[] %constant.14) } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true, 1, /*pipeline_use_tree=*/false, /*process_different_sized_ops=*/true, CollectivePipeliner::PipeliningDirection::kForward, IsAllGather) .value()); XLA_VLOG_LINES(1, module->ToString()); auto* root = module->entry_computation()->root_instruction(); // Check that the all-gather can be pipelined after we had already a previous // round of pipelining performed previously for another op. (in this case // AllReduce). EXPECT_THAT( root, op::DynamicUpdateSlice( op::DynamicUpdateSlice(_, op::AllGather(), _, _, _), op::AllReduce(op::DynamicSlice(op::DynamicUpdateSlice(), _, _, _)), op::GetTupleElement(), op::Constant(), op::Constant())); }
CollectivePipelinerTest_TransformIncrementByTwo
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, TransformIncrementByTwo) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(3) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,8,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(2) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.5, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) ar.1 = bf16[1,8,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, ar.1, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5) } ENTRY entry { c0 = s32[] constant(0) p0 = bf16[3,8,128] parameter(0) tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true).value()); XLA_VLOG_LINES(1, module->ToString()); const HloInstruction* root = module->entry_computation()->root_instruction(); EXPECT_THAT(root, op::DynamicUpdateSlice(_, op::AllReduce(), _, _, _)); const HloInstruction* sliced = root->operand(1)->operand(0); EXPECT_EQ(sliced->opcode(), HloOpcode::kDynamicSlice); const HloInstruction* index = sliced->operand(1); EXPECT_EQ(index->opcode(), HloOpcode::kGetTupleElement); EXPECT_EQ(index->tuple_index(), 3); const HloInstruction* while_inst = index->operand(0); EXPECT_EQ(while_inst->opcode(), HloOpcode::kWhile); const HloInstruction* while_root = while_inst->while_body()->root_instruction(); EXPECT_EQ(while_root->opcode(), HloOpcode::kTuple); const HloInstruction* dyn_upd = while_root->operand(1); EXPECT_EQ(dyn_upd->opcode(), HloOpcode::kDynamicUpdateSlice); const HloInstruction* dyn_upd2 = dyn_upd->operand(0); EXPECT_EQ(dyn_upd2->opcode(), HloOpcode::kDynamicUpdateSlice); const HloInstruction* prev_ar = dyn_upd2->operand(1); EXPECT_EQ(prev_ar->opcode(), HloOpcode::kAllReduce); const HloInstruction* dyn_slice_top = prev_ar->operand(0); EXPECT_EQ(dyn_slice_top->opcode(), HloOpcode::kDynamicSlice); const HloInstruction* get_tuple_value = dyn_slice_top->operand(0); const HloInstruction* get_tuple_index = dyn_slice_top->operand(1); EXPECT_EQ(get_tuple_value->opcode(), HloOpcode::kGetTupleElement); EXPECT_EQ(get_tuple_index->opcode(), HloOpcode::kGetTupleElement); EXPECT_EQ(get_tuple_value->tuple_index(), 1); EXPECT_EQ(get_tuple_index->tuple_index(), 3); }
CollectivePipelinerTest_TransformIncrementByTwoFormat
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, TransformIncrementByTwoFormat) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,16,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(3) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,16,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.396 = bf16[3,16,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(2) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,16,128] dynamic-slice(get-tuple-element.396, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,16,128} mul = bf16[1,16,128] multiply(dynamic-slice.99, dynamic-slice.99) ar.1 = bf16[1,16,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 ds.1 = bf16[1,8,128] dynamic-slice(ar.1, constant.2561, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, ds.1, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,16,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.396) } ENTRY entry { c0 = s32[] constant(0) p0 = bf16[3,16,128] parameter(0) c1 = bf16[] constant(0) b1 = bf16[3,8,128] broadcast(c1), dimensions={} tuple = (s32[], bf16[3,8,128], bf16[3,16,128]) tuple(c0, b1, p0) while = (s32[], bf16[3,8,128], bf16[3,16,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true).value()); XLA_VLOG_LINES(1, module->ToString()); const HloInstruction* root = module->entry_computation()->root_instruction(); EXPECT_THAT( root, op::DynamicUpdateSlice( _, op::DynamicSlice(op::AllReduce(op::GetTupleElement()), _, _, _), _, _, _)); }
CollectivePipelinerTest_TransformIncrementByTwoFormatTranspose
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, TransformIncrementByTwoFormatTranspose) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,16,128], bf16[3,16,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(3) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,16,128], bf16[3,16,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,16,128] get-tuple-element(param), index=1 get-tuple-element.396 = bf16[3,16,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(2) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,16,128] dynamic-slice(get-tuple-element.396, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,16,128} mul = bf16[1,16,128] multiply(dynamic-slice.99, dynamic-slice.99) reshape.1 = bf16[2,16,64] reshape(mul) ar.1 = bf16[2,16,64] all-reduce(reshape.1), replica_groups={}, to_apply=add, channel_id=1 transpose.1 = bf16[64,2,16] transpose(ar.1), dimensions={2,0,1} reshape.2 = bf16[1,16,128] reshape(transpose.1) dynamic-update-slice.35 = bf16[3,16,128] dynamic-update-slice(get-tuple-element.395, reshape.2, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,16,128], bf16[3,16,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.396) } ENTRY entry { c0 = s32[] constant(0) p0 = bf16[3,16,128] parameter(0) c1 = bf16[] constant(0) b1 = bf16[3,16,128] broadcast(c1), dimensions={} tuple.1 = (s32[], bf16[3,16,128], bf16[3,16,128]) tuple(c0, b1, p0) while = (s32[], bf16[3,16,128], bf16[3,16,128]) while(tuple.1), condition=while_cond, body=while_body ROOT gte1 = bf16[3,16,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true).value()); XLA_VLOG_LINES(1, module->ToString()); const HloInstruction* root = module->entry_computation()->root_instruction(); EXPECT_THAT( root, op::DynamicUpdateSlice( _, op::Reshape(op::Transpose(op::AllReduce(op::GetTupleElement()))), _, _, _)); }
CollectivePipelinerTest_TransformIncrementIndexByOne
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, TransformIncrementIndexByOne) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(3) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,8,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.5, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) ar.1 = bf16[1,8,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, ar.1, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5) } ENTRY entry { c0 = s32[] constant(0) p0 = bf16[3,8,128] parameter(0) tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true).value()); XLA_VLOG_LINES(1, module->ToString()); const HloInstruction* root = module->entry_computation()->root_instruction(); EXPECT_THAT(root, op::DynamicUpdateSlice(_, op::AllReduce(), _, _, _)); const HloInstruction* sliced = root->operand(1)->operand(0); EXPECT_EQ(sliced->opcode(), HloOpcode::kDynamicSlice); const HloInstruction* index = sliced->operand(1); EXPECT_EQ(index->opcode(), HloOpcode::kGetTupleElement); EXPECT_EQ(index->tuple_index(), 3); const HloInstruction* while_inst = index->operand(0); EXPECT_EQ(while_inst->opcode(), HloOpcode::kWhile); const HloInstruction* while_root = while_inst->while_body()->root_instruction(); EXPECT_EQ(while_root->opcode(), HloOpcode::kTuple); const HloInstruction* dyn_upd = while_root->operand(1); EXPECT_EQ(dyn_upd->opcode(), HloOpcode::kDynamicUpdateSlice); const HloInstruction* dyn_upd2 = dyn_upd->operand(0); EXPECT_EQ(dyn_upd2->opcode(), HloOpcode::kDynamicUpdateSlice); const HloInstruction* prev_ar = dyn_upd2->operand(1); EXPECT_EQ(prev_ar->opcode(), HloOpcode::kAllReduce); const HloInstruction* dyn_slice_top = prev_ar->operand(0); EXPECT_EQ(dyn_slice_top->opcode(), HloOpcode::kDynamicSlice); const HloInstruction* get_tuple_value = dyn_slice_top->operand(0); const HloInstruction* get_tuple_index = dyn_slice_top->operand(1); EXPECT_EQ(get_tuple_value->opcode(), HloOpcode::kGetTupleElement); EXPECT_EQ(get_tuple_index->opcode(), HloOpcode::kGetTupleElement); EXPECT_EQ(get_tuple_value->tuple_index(), 1); EXPECT_EQ(get_tuple_index->tuple_index(), 3); }
CollectivePipelinerTest_TransformIncrementIndexByOneBackwards
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, TransformIncrementIndexByOneBackwards) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,1,2,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(3) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,1,2,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.k = bf16[3,1,2,128] get-tuple-element(param), index=2 constant.2561 = s32[] constant(0) constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.k = bf16[1,1,2,128] dynamic-slice(get-tuple-element.k, select.1348, constant.2561, constant.2561, constant.2561), dynamic_slice_sizes={1,1,2,128} r = bf16[1,2,128] reshape(dynamic-slice.k) a = bf16[1,2,128] add(r, r), control-predecessors={constant.2559} ag = bf16[1,8,128] all-gather(a), dimensions={1}, replica_groups={} dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.395, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, ag) ar.1 = bf16[1,8,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, ar.1, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,1,2,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.k), control-predecessors={a} } ENTRY entry { c0 = s32[] constant(0) p0 = bf16[3,8,128] parameter(0) p1 = bf16[3,1,2,128] parameter(1) tuple = (s32[], bf16[3,8,128], bf16[3,1,2,128]) tuple(c0, p0, p1) while = (s32[], bf16[3,8,128], bf16[3,1,2,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true, 0, /*pipeline_use_tree=*/false, /*process_different_sized_ops=*/false, CollectivePipeliner::PipeliningDirection::kBackward, IsAllGather) .value()); XLA_VLOG_LINES(1, module->ToString()); const int64_t while_count = absl::c_count_if( module->entry_computation()->instructions(), [](const HloInstruction* instruction) { return HloPredicateIsOp<HloOpcode::kWhile>(instruction); }); EXPECT_EQ(while_count, 1); const HloInstruction* while_instr = FindInstruction(module.get(), HloOpcode::kWhile); const HloInstruction* tuple = while_instr->operand(0); EXPECT_TRUE(tuple->HasControlDependencies()); EXPECT_EQ(tuple->control_predecessors().size(), 1); const HloInstruction* add_instr = tuple->control_predecessors()[0]; EXPECT_EQ(add_instr->opcode(), HloOpcode::kAdd); const HloComputation* comp = while_instr->while_body(); const HloInstruction* root_loop = comp->root_instruction(); EXPECT_TRUE(root_loop->HasControlDependencies()); EXPECT_EQ(root_loop->control_predecessors().size(), 1); const HloInstruction* add_instr_loop = root_loop->control_predecessors()[0]; EXPECT_EQ(add_instr_loop->opcode(), HloOpcode::kAdd); }
CollectivePipelinerTest_TransformIncrementIndexByOneNoReuse
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, TransformIncrementIndexByOneNoReuse) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(3) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,8,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.5, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) ar.1 = bf16[1,8,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, ar.1, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5) } ENTRY entry { c0 = s32[] constant(0) p0 = bf16[3,8,128] parameter(0) tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer( module.get(), /*last_run=*/true, 0, false, true, CollectivePipeliner::PipeliningDirection::kForward, HloPredicateIsOp<HloOpcode::kAllReduce>, /*acceptable_formatting=*/ [](const HloInstruction* i) { return true; }, /*reuse_pipelined_op_buffer=*/ [](const HloInstruction* i) { return false; }) .value()); XLA_VLOG_LINES(1, module->ToString()); HloInstruction* while_instr = FindInstruction(module.get(), HloOpcode::kWhile); EXPECT_EQ(while_instr->shape().tuple_shapes_size(), 5); }
CollectivePipelinerTest_TransformIncrementIndexByOneNotFirstIdx
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, TransformIncrementIndexByOneNotFirstIdx) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[8,3,128], bf16[8,3,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(3) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[8,3,128], bf16[8,3,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[8,3,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[8,3,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[8,1,128] dynamic-slice(get-tuple-element.5, constant.2561, select.1348, constant.2561), dynamic_slice_sizes={8,1,128} mul = bf16[8,1,128] multiply(dynamic-slice.99, dynamic-slice.99) ar.1 = bf16[8,1,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 dynamic-update-slice.35 = bf16[8,3,128] dynamic-update-slice(get-tuple-element.395, ar.1, constant.2561, select.1348, constant.2561) ROOT tuple = (s32[], bf16[8,3,128], bf16[8,3,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5) } ENTRY entry { c0 = s32[] constant(0) p0 = bf16[8,3,128] parameter(0) tuple = (s32[], bf16[8,3,128], bf16[8,3,128]) tuple(c0, p0, p0) while = (s32[], bf16[8,3,128], bf16[8,3,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[8,3,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true).value()); XLA_VLOG_LINES(1, module->ToString()); const HloInstruction* root = module->entry_computation()->root_instruction(); EXPECT_THAT(root, op::DynamicUpdateSlice(_, op::AllReduce(), _, _, _)); const HloInstruction* sliced = root->operand(1)->operand(0); EXPECT_EQ(sliced->opcode(), HloOpcode::kDynamicSlice); const HloInstruction* index = sliced->operand(2); EXPECT_EQ(index->opcode(), HloOpcode::kGetTupleElement); EXPECT_EQ(index->tuple_index(), 3); const HloInstruction* while_inst = index->operand(0); EXPECT_EQ(while_inst->opcode(), HloOpcode::kWhile); const HloInstruction* while_root = while_inst->while_body()->root_instruction(); EXPECT_EQ(while_root->opcode(), HloOpcode::kTuple); const HloInstruction* dyn_upd = while_root->operand(1); EXPECT_EQ(dyn_upd->opcode(), HloOpcode::kDynamicUpdateSlice); const HloInstruction* dyn_upd2 = dyn_upd->operand(0); EXPECT_EQ(dyn_upd2->opcode(), HloOpcode::kDynamicUpdateSlice); const HloInstruction* prev_ar = dyn_upd2->operand(1); EXPECT_EQ(prev_ar->opcode(), HloOpcode::kAllReduce); const HloInstruction* dyn_slice_top = prev_ar->operand(0); EXPECT_EQ(dyn_slice_top->opcode(), HloOpcode::kDynamicSlice); const HloInstruction* get_tuple_value = dyn_slice_top->operand(0); const HloInstruction* get_tuple_index = dyn_slice_top->operand(2); EXPECT_EQ(get_tuple_value->opcode(), HloOpcode::kGetTupleElement); EXPECT_EQ(get_tuple_index->opcode(), HloOpcode::kGetTupleElement); EXPECT_EQ(get_tuple_value->tuple_index(), 1); EXPECT_EQ(get_tuple_index->tuple_index(), 3); }
CollectivePipelinerTest_TransformIncrementIndexByOneNotFirstIdxSink
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, TransformIncrementIndexByOneNotFirstIdxSink) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(3) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.35 = bf16[3,8,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.35, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) ar.1 = bf16[1,8,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 %c = bf16[] custom-call(), custom_call_target="Boh" %b = bf16[1,8,128] broadcast(c), dimensions={} %a = bf16[1,8,128] add(ar.1, b) dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, a, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.35), control-predecessors={select.1348} } ENTRY entry { c0 = s32[] constant(0) p0 = bf16[3,8,128] parameter(0) tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true, /*level_to_operate_on=*/0, /*pipeline_use_tree=*/true, /*process_different_sized_ops=*/true, CollectivePipeliner::kForwardSink) .value()); XLA_VLOG_LINES(1, module->ToString()); const HloInstruction* while_instr = FindInstruction(module.get(), HloOpcode::kWhile); const HloComputation* comp = while_instr->while_body(); const HloInstruction* root_loop = comp->root_instruction(); EXPECT_TRUE(root_loop->HasControlDependencies()); EXPECT_EQ(root_loop->control_predecessors().size(), 1); const HloInstruction* select_instr_loop = root_loop->control_predecessors()[0]; EXPECT_EQ(select_instr_loop->opcode(), HloOpcode::kSelect); }
CollectivePipelinerTest_TransformNegativeIndexIterationToZero
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, TransformNegativeIndexIterationToZero) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(0) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,8,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.5, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) ar.1 = bf16[1,8,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, ar.1, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5) } ENTRY entry { c0 = s32[] constant(-3) p0 = bf16[3,8,128] parameter(0) tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/false).value()); XLA_VLOG_LINES(1, module->ToString()); auto* root = module->entry_computation()->root_instruction(); EXPECT_THAT(root, op::DynamicUpdateSlice( _, op::CustomCall(op::AllReduce(op::DynamicSlice( op::GetTupleElement(op::While()), op::GetTupleElement(), op::Constant(), op::Constant())), op::Constant()), op::GetTupleElement(), op::Constant(), op::Constant())); }
CollectivePipelinerTest_TransformRecvSendBackwards
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; };
CollectivePipelinerTest_TransformWithAg
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, TransformWithAg) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(0) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,8,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.5, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) rs.1 = bf16[1,1,128] reduce-scatter(mul), replica_groups={}, to_apply=add, channel_id=1, dimensions={1} ag.1 = bf16[1,8,128] all-gather(rs.1), replica_groups={}, channel_id=2, dimensions={1} dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, ag.1, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5) } ENTRY entry { c0 = s32[] constant(-3) p0 = bf16[3,8,128] parameter(0) cc = bf16[] constant(0) tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true, 0, /*pipeline_use_tree=*/false, /*process_different_sized_ops=*/true, CollectivePipeliner::PipeliningDirection::kForward, IsAllGather) .value()); XLA_VLOG_LINES(1, module->ToString()); auto* root = module->entry_computation()->root_instruction(); EXPECT_THAT(root, op::DynamicUpdateSlice( _, op::AllGather(op::GetTupleElement(op::While())), op::GetTupleElement(), op::Constant(), op::Constant())); }
CollectivePipelinerTest_TransformWithAgInsertCustomCall
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, TransformWithAgInsertCustomCall) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(0) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,8,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) constant.2561 = s32[] constant(0) add.230 = s32[] add(get-tuple-element.394, constant.2557) dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.5, get-tuple-element.394, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) rs.1 = bf16[1,1,128] reduce-scatter(mul), replica_groups={}, to_apply=add, channel_id=1, dimensions={1} ag.1 = bf16[1,8,128] all-gather(rs.1), replica_groups={}, channel_id=2, dimensions={1} dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, ag.1, get-tuple-element.394, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5) } ENTRY entry { c0 = s32[] constant(-8) p0 = bf16[3,8,128] parameter(0) cc = bf16[] constant(0) tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/false, 0, /*pipeline_use_tree=*/false, /*process_different_sized_ops=*/true, CollectivePipeliner::PipeliningDirection::kForward, IsAllGather) .value()); XLA_VLOG_LINES(1, module->ToString()); RunOptimizer(module.get(), /*last_run=*/true, 1).value(); XLA_VLOG_LINES(1, module->ToString()); auto* root = module->entry_computation()->root_instruction(); // Matching the pattern we expect for the output of the loop when an // all-gather is pipelined through the loop. We dynamic-slice the stacked // data, perform the all-gather and then put it in the stacked data again. EXPECT_THAT(root, op::DynamicUpdateSlice( _, op::AllGather(op::GetTupleElement(op::While())), op::GetTupleElement(), op::Constant(), op::Constant())); }
CollectivePipelinerTest_TransformWithAgWithFormatting
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, TransformWithAgWithFormatting) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,9,128], bf16[3,9,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(0) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,9,128], bf16[3,9,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,9,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,9,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,9,128] dynamic-slice(get-tuple-element.5, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,9,128} mul = bf16[1,9,128] multiply(dynamic-slice.99, dynamic-slice.99) cpd = bf16[] constant(0) %pd = bf16[1,16,128] pad(mul, cpd), padding=0_0x0_7x0_0 rs.1 = bf16[1,2,128] reduce-scatter(pd), replica_groups={}, to_apply=add, channel_id=1, dimensions={1} ag.1 = bf16[1,16,128] all-gather(rs.1), replica_groups={}, channel_id=2, dimensions={1} slc = bf16[1,9,128] slice(ag.1), slice={[0:1], [0:9], [0:128]} dynamic-update-slice.35 = bf16[3,9,128] dynamic-update-slice(get-tuple-element.395, slc, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,9,128], bf16[3,9,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5) } ENTRY entry { c0 = s32[] constant(-3) p0 = bf16[3,9,128] parameter(0) cc = bf16[] constant(0) tuple = (s32[], bf16[3,9,128], bf16[3,9,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,9,128], bf16[3,9,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,9,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true, 0, /*pipeline_use_tree=*/false, /*process_different_sized_ops=*/true, CollectivePipeliner::PipeliningDirection::kForward, IsAllGather) .value()); XLA_VLOG_LINES(1, module->ToString()); auto* root = module->entry_computation()->root_instruction(); EXPECT_THAT(root, op::DynamicUpdateSlice( _, op::Slice(op::AllGather(op::GetTupleElement(op::While()))), op::GetTupleElement(), op::Constant(), op::Constant())); }
CollectivePipelinerTest_UpdateSendRecvChannelIdForHostTransfers
xla/service/collective_pipeliner_test.cc
absl::Status UpdateControlDependencies(HloInstruction* original, HloInstruction* new_instr, const InstructionMap& cloned_map) { for (auto* pred : original->control_predecessors()) { auto it = cloned_map.find(pred); if (it == cloned_map.end()) { continue; } TF_RETURN_IF_ERROR(it->second->AddControlDependencyTo(new_instr)); } return absl::OkStatus(); } bool AllIndicesConstantsExceptOne( const HloDynamicUpdateSliceInstruction* dyn_update, int64_t index) { if (dyn_update->operand(index)->IsConstant()) { return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (i == index) { continue; } if (!dyn_update->operand(i)->IsConstant()) { return false; } } return true; } std::optional<int> GetSlicedDimension( const HloDynamicUpdateSliceInstruction* dyn_update) { std::optional<int> sliced_dim; for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { const HloInstruction* idx = dyn_update->operand(i); if (!idx->IsConstant()) { if (sliced_dim.has_value()) { return std::nullopt; } sliced_dim = i - dyn_update->first_index_operand_number(); continue; } if (Cast<HloConstantInstruction>(idx)->literal().GetFirstInteger() != 0) { return std::nullopt; } } return sliced_dim; } bool CheckIndexIsMonotonic( const HloInstruction* index, const absl::flat_hash_map<const HloInstruction*, Range>& induction_map) { // Because the only math operations supported by RecursivelyIdentifyRange() // are only sub/add then checking that we can compute the range here is enough // to guarantee that the index is monotonic if the base index is monotonic. If // we want to make the function more powerful we need to have a more // sophisticated check for monotonicity. Range range = RecursivelyIdentifyRange(index, induction_map); VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); return !range.IsEmpty() && range.IsLinear(); } VLOG(5) << "Range for: " << index->ToString() << " " << range.ToString(); bool CheckParameterUsageIsCompatible(const HloInstruction* gte, const HloInstruction* dus, const HloInstruction* dus_idx, int64_t sliced_index) { for (auto* user : gte->users()) { // Expected all users are dynamic-slices if (dus != user) { VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " "or the dynamic-update-slice for the output." << user->ToString(); return false; } // Expected same index as dynamic-update-slice(). if (user->operand(static_cast<HloDynamicSliceInstruction*>(user) ->first_index_operand_number() + sliced_index) != dus_idx) { VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " "dynamic-update-slice() " << user->ToString(); return false; } } return true; } VLOG(5) << "CheckParameterUsageIsCompatible(): User not a dynamic slice " VLOG(5) << "CheckParameterUsageIsCompatible(): Idx is not the same as " std::optional<int64_t> GetLevelFromCustomCall(const HloInstruction* instr) { if (!instr->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep)) { return std::nullopt; } return Cast<HloConstantInstruction>(instr->operand(1)) ->literal() .GetFirstInteger(); } CollectDynamicSliceIndicesIfConstant(HloInstruction* instr) { CHECK_EQ(instr->opcode(), HloOpcode::kDynamicSlice); std::vector<HloInstruction*> indices; HloDynamicSliceInstruction* dyn_slice = Cast<HloDynamicSliceInstruction>(instr); for (int64_t i = dyn_slice->first_index_operand_number(); i < instr->operand_count(); ++i) { HloInstruction* operand = dyn_slice->mutable_operand(i); CHECK_EQ(operand->shape().dimensions_size(), 0); std::vector<std::pair<HloInstruction*, int>> stack( 1, std::make_pair(operand, 0)); absl::flat_hash_set<HloInstruction*> visited; while (!stack.empty()) { auto& [curr_instr, operand_idx] = stack.back(); if (operand_idx == curr_instr->operand_count()) { indices.push_back(curr_instr); stack.pop_back(); continue; } HloInstruction* next_operand = curr_instr->mutable_operand(operand_idx++); if (next_operand->opcode() == HloOpcode::kParameter || next_operand->HasSideEffect()) { return std::nullopt; } if (visited.insert(next_operand).second) { stack.push_back(std::make_pair(next_operand, 0)); } } } return indices; } [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, [&](auto kType) -> std::optional<Literal> { if constexpr (primitive_util::IsIntegralType(kType)) { using NativeT = typename primitive_util::NativeTypeOf<kType>; CHECK_LE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::max())); CHECK_GE(value, static_cast<absl::int128>( std::numeric_limits<NativeT>::min())); return LiteralUtil::CreateR0(static_cast<NativeT>(value)); } return std::nullopt; }, bool CollectSimpleDependencies(HloInstruction* i, std::vector<HloInstruction*>& deps_vector, absl::flat_hash_set<HloInstruction*>& deps_set) { if (i->opcode() == HloOpcode::kDynamicSlice) { auto indices = CollectDynamicSliceIndicesIfConstant(i); if (!indices.has_value()) { return false; } deps_vector.insert(deps_vector.end(), indices->begin(), indices->end()); deps_set.insert(indices->begin(), indices->end()); return true; } for (HloInstruction* op : i->mutable_operands()) { absl::InlinedVector<HloInstruction*, 4> to_add; if (op->opcode() == HloOpcode::kBroadcast) { to_add.push_back(op); if (deps_set.insert(op).second) { op = op->mutable_operand(0); if (op->opcode() == HloOpcode::kConstant) { if (deps_set.insert(op).second) { to_add.push_back(op); } } } } deps_vector.insert(deps_vector.end(), to_add.rbegin(), to_add.rend()); } return true; } CheckStoreIntoSliceIsCompatible(HloInstruction* instr, const HloComputation* while_body, int64_t level_to_operate_on, bool multi_uses_pipelining, HloPredicate acceptable_formatting) { if ((!multi_uses_pipelining && instr->user_count() != 1) || instr->operand_count() != 1 || instr->HasControlDependencies()) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } // Set to collect instructions that have been already added. absl::flat_hash_set<HloInstruction*> added_instructions; HloInstruction* folded_instr = instr; std::vector<HloInstruction*> formatting_ops; // Returns if this is an acceptable user of a pipelined instruction. // Generic elementwise ops can have multiple operands that require the inputs // of being saved across the loop. So protect them through // "multi_uses_pipelining" flag. auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; // Returns if this instruction is a dynamic-update-slice inserting the value // into a bigger buffer that we are going to pipeline to the next iteration. auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; HloDynamicUpdateSliceInstruction* final_slice_insertion = nullptr; std::vector<std::pair<HloInstruction*, int>> stack; absl::flat_hash_map<HloInstruction*, int32_t> formatting_map; stack.push_back(std::make_pair(folded_instr, 0)); // Post order traversal to discover formatting instructions. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { formatting_map[instr] = 0; } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (!is_acceptable_user(next_user)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } if (final_slice_insertion == nullptr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } for (auto& op : formatting_map) { for (const HloInstruction* operand : final_slice_insertion->operands()) { if (formatting_map.count(operand)) { ++op.second; } } } stack.push_back(std::make_pair(folded_instr, 0)); added_instructions.clear(); // Post order traversal to determine the insert instruction order. while (!stack.empty()) { auto& data = stack.back(); HloInstruction* instr = data.first; if (data.second == 0 && instr != folded_instr) { if (!CollectSimpleDependencies(instr, formatting_ops, added_instructions)) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } formatting_ops.push_back(instr); } if (data.second == instr->user_count()) { stack.pop_back(); continue; } HloInstruction* next_user = instr->users()[data.second++]; if (is_final_slice_insertion(next_user)) { if ((final_slice_insertion != nullptr && final_slice_insertion != next_user) || next_user->user_count() != 1 || next_user->operand(1) != instr) { return std::make_pair(nullptr, std::vector<HloInstruction*>{}); } final_slice_insertion = Cast<HloDynamicUpdateSliceInstruction>(next_user); continue; } if (--formatting_map[next_user] > 0) { continue; } if (added_instructions.insert(next_user).second) { stack.push_back(std::make_pair(next_user, 0)); } } return std::make_pair(final_slice_insertion, formatting_ops); } auto is_acceptable_user = [&](HloInstruction* i) { if (i->HasControlDependencies() || !acceptable_formatting(i)) { return false; } if (i->opcode() == HloOpcode::kReduce && (ShapeUtil::ElementsIn(i->shape()) == ShapeUtil::ElementsIn(instr->operand(0)->shape()) || ShapeUtil::ElementsIn(instr->operand(0)->shape()) < 1024)) { return true; } return HloPredicateIsOp<HloOpcode::kSlice, HloOpcode::kDynamicSlice, HloOpcode::kPad, HloOpcode::kCollectivePermute, HloOpcode::kConvert, HloOpcode::kReshape, HloOpcode::kAllReduce, HloOpcode::kTranspose, HloOpcode::kBroadcast>(i) || (multi_uses_pipelining && i->IsElementwise()) || i->IsCustomCall(CollectivePipeliner::kInsertedByPreviousStep); }; auto is_final_slice_insertion = [&](HloInstruction* i) { HloDynamicUpdateSliceInstruction* dyn_update = DynCast<HloDynamicUpdateSliceInstruction>(i); if (dyn_update == nullptr || dyn_update->user_count() != 1) { return false; } if (level_to_operate_on == 0) { if (dyn_update->users()[0] == while_body->root_instruction()) { return true; } return false; } for (int64_t i = dyn_update->first_index_operand_number(); i < dyn_update->operand_count(); ++i) { if (auto level = GetLevelFromCustomCall(dyn_update->operand(i))) { if (*level == level_to_operate_on) { return true; } return false; } } return false; }; bool IsLoopIterator(const HloInstruction* instr, int64_t loop_iteration_tuple_idx) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return instr->tuple_index() == loop_iteration_tuple_idx; } std::vector<HloInstruction*> CollectDependenciesToPipeline( HloInstruction* source_op, absl::Span<HloInstruction* const> ops) { absl::flat_hash_set<HloInstruction*> formatting_set(ops.begin(), ops.end()); formatting_set.insert(source_op); std::vector<HloInstruction*> to_return; absl::flat_hash_set<HloInstruction*> already_inserted; for (const HloInstruction* op : ops) { for (HloInstruction* operand : op->operands()) { if (!formatting_set.count(operand)) { formatting_set.insert(operand); to_return.push_back(operand); } } } return to_return; } std::optional<std::vector<HloInstruction*>> CollectIndependentOperandChain( HloInstruction* instr, int64_t loop_iter, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { std::vector<HloInstruction*> chain; absl::flat_hash_set<const HloInstruction*> visited_set({instr}); std::vector<std::pair<HloInstruction*, int>> stack(1, {instr, 0}); auto is_loop_variant_parameter_input = [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; while (!stack.empty()) { auto& curr = stack.back(); if (curr.second == curr.first->operand_count()) { if (curr.first != instr) { chain.push_back(curr.first); } stack.pop_back(); continue; } HloInstruction* curr_operand = curr.first->mutable_operand(curr.second++); if (curr_operand->opcode() == HloOpcode::kParameter) { continue; } if (is_loop_variant_parameter_input(curr_operand) && !should_allow_loop_variant_parameter_in_chain(curr_operand)) { return std::nullopt; } if (visited_set.insert(curr_operand).second) { stack.emplace_back(curr_operand, 0); } } for (auto* chain_instr : chain) { // Allow tokens in the chain. if (chain_instr->opcode() == HloOpcode::kAfterAll) { continue; } if (chain_instr->opcode() == HloOpcode::kRecvDone) { // Since we allow tokens in the chain, we need to exclude Recv-done in // the chain, to prevent pipelining Recv/Recv-done by accident. return std::nullopt; } const bool all_users_in_chain = absl::c_all_of( chain_instr->users(), [&visited_set](const HloInstruction* u) { return visited_set.contains(u); }); const bool is_scalar_shaped = ShapeUtil::IsEffectiveScalar(chain_instr->shape()); if (!all_users_in_chain) { // Whether we should allow loop variant parameter in the operand chain of // the collective. bool allow_loop_variant_parameter_in_chain = (chain_instr->opcode() != HloOpcode::kGetTupleElement || chain_instr->operand(0)->opcode() != HloOpcode::kParameter || !should_allow_loop_variant_parameter_in_chain(chain_instr)); // Whether we should allow loop invariant instructions in the operand // chain of the collective. bool add_loop_invariant_op_in_chain = (should_add_loop_invariant_op_in_chain && loop_invariant_instructions.contains(chain_instr)); if ((!loop_invariant_params.contains(chain_instr) && !is_scalar_shaped && allow_loop_variant_parameter_in_chain) && !add_loop_invariant_op_in_chain) { return std::nullopt; } } } return std::move(chain); } [&loop_invariant_params, loop_iter](const HloInstruction* instr) { if (instr->opcode() != HloOpcode::kGetTupleElement || instr->operand(0)->opcode() != HloOpcode::kParameter) { return false; } return !IsLoopIterator(instr, loop_iter) && !loop_invariant_params.count(instr); }; std::optional<std::vector<HloInstruction*>> CollectChainsToPushBackwards( HloInstruction* instr, int64_t loop_iter, const HloComputation* while_body, int64_t level_to_operate_on, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_params, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, const absl::flat_hash_set<const HloInstruction*>& loop_invariant_instructions, bool should_add_loop_invariant_op_in_chain) { if (instr->HasControlDependencies() && !should_allow_control_dependencies) { return std::nullopt; } return CollectIndependentOperandChain( instr, loop_iter, loop_invariant_params, should_allow_loop_variant_parameter_in_chain, loop_invariant_instructions, should_add_loop_invariant_op_in_chain); } std::optional<int64_t> FindOutputIndexForDynamicUpdateSlice( const HloInstruction* dus, const HloInstruction* root_instr) { std::optional<int64_t> output_idx; while (dus->opcode() == HloOpcode::kDynamicUpdateSlice) { if (dus->user_count() != 1) { output_idx = std::nullopt; break; } if (dus->users()[0] == root_instr) { auto indices = root_instr->OperandIndices(dus); if (indices.size() != 1) { output_idx = std::nullopt; break; } output_idx = indices[0]; break; } dus = Cast<HloDynamicUpdateSliceInstruction>(dus->users()[0]); } return output_idx; } std::vector<HloInstruction*> MapNewOperands( absl::Span<HloInstruction* const> operands, const InstructionMap& clone_map, bool allow_unmapped = false) { std::vector<HloInstruction*> new_operands; new_operands.reserve(operands.size()); for (HloInstruction* operand : operands) { auto it = clone_map.find(operand); HloInstruction* mapped_operand = operand; CHECK(it != clone_map.end() || allow_unmapped) << operand->ToString() << " not present in map"; if (it != clone_map.end()) { mapped_operand = it->second; } new_operands.push_back(mapped_operand); } return new_operands; } void UpdateInstructionChannelId(HloInstruction* cloned_instr, int64_t& next_channel_id) { // Avoid updating Send and Recv instructions because pipelined Send and Recv // instructions should keep the same channel-id to indicate that the group of // instructions need to cooperate. if (const auto* send_recv_instr = DynCast<HloSendRecvInstruction>(cloned_instr)) { if (!send_recv_instr->is_host_transfer()) { return; } } if (auto* channel_instr = DynCast<HloChannelInstruction>(cloned_instr)) { if (channel_instr->opcode() == HloOpcode::kSendDone || channel_instr->opcode() == HloOpcode::kRecvDone) { auto* operand = channel_instr->operand(0); CHECK(operand->opcode() == HloOpcode::kSend || operand->opcode() == HloOpcode::kRecv); channel_instr->set_channel_id( Cast<HloChannelInstruction>(operand)->channel_id()); return; } if (channel_instr->channel_id()) { channel_instr->set_channel_id(next_channel_id++); } } } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } absl::StatusOr<HloInstruction*> CloneBackwardChain( Comp& target_computation, const WhileMoveInfo& move_info, InstructionMap& clone_map, int64_t loop_iter_idx, int64_t& next_channel_id, LoopVariantParameterInfo* loop_variant_parameter_info = nullptr) { std::vector<HloInstruction*> to_clone(move_info.formatting_ops.begin(), move_info.formatting_ops.end()); to_clone.push_back(move_info.collective_to_move); HloInstruction* last_cloned = nullptr; for (auto* chain_op : to_clone) { // Do not clone a loop iterator or an op that is already cloned. if (IsLoopIterator(chain_op, loop_iter_idx) || clone_map.contains(chain_op)) { continue; } auto new_operands = MapNewOperands(chain_op->operands(), clone_map); HloInstruction* cloned = target_computation.AddInstruction( chain_op->CloneWithNewOperands(chain_op->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(chain_op, cloned, clone_map)); UpdateInstructionChannelId(cloned, next_channel_id); clone_map[chain_op] = cloned; last_cloned = cloned; if (loop_variant_parameter_info != nullptr && chain_op->opcode() == HloOpcode::kGetTupleElement && chain_op->operand(0)->opcode() == HloOpcode::kParameter && chain_op->tuple_index() != loop_iter_idx) { loop_variant_parameter_info->push_back( std::make_pair(chain_op->tuple_index(), cloned)); } } CHECK_NE(last_cloned, nullptr); return last_cloned; } int64_t WhileLoopAnalysis::GetDUSIndex(const HloInstruction* dus) const { auto it = dus_index_map_.find(dus); CHECK(it != dus_index_map_.end()); return it->second; } void WhileLoopAnalysis::ExtractLoopInvariantOps() { for (HloInstruction* inst : while_->while_body()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kConstant) { invariant_loop_instructions_.insert(inst); continue; } if (invariant_loop_instructions_.contains(inst)) { continue; } // Nodes that only consume loop invariants are also invariants. bool should_add = true; for (const HloInstruction* operand : inst->operands()) { should_add &= (invariant_loop_instructions_.contains(operand) || invariant_loop_parameters_.contains(operand)); } if (should_add) { invariant_loop_instructions_.insert(inst); } } } bool WhileLoopAnalysis::ComputeLoopStatistics() { // Loop iteration count already computed. This means a previous analysis as // been successful and we don't need to do anything. if (loop_iteration_count_) { return true; } std::optional<ParsedWhileLoop> parsed_loop = PatternMatchParseWhileLoop(while_); if (!parsed_loop || !parsed_loop->static_while_loop) { return false; } if (!IsSupportedLoopIndexType( while_->shape() .tuple_shapes(parsed_loop->static_while_loop->induction_var_index) .element_type())) { return false; } const HloInstruction* loop_root = while_->while_body()->root_instruction(); const int64_t bitwidth = primitive_util::BitWidth( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const bool is_signed = primitive_util::IsSignedIntegralType( loop_root->operand(parsed_loop->static_while_loop->induction_var_index) ->shape() .element_type()); const ConstantValue bound = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->loop_bound, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->loop_bound, bitwidth); const ConstantValue increment = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->step_size, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->step_size, bitwidth); loop_start_ = is_signed ? ConstantValue::GetSigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth) : ConstantValue::GetUnsigned( parsed_loop->static_while_loop->induction_var_init_value, bitwidth); auto iteration_range = bound.sub(*loop_start_); auto iter_count = iteration_range.div(increment); loop_iteration_count_ = iteration_range.mod(increment).gt( ConstantValue::GetZero(increment.GetBitwidth(), increment.IsSigned())) ? iter_count.add(ConstantValue::GetOne(increment.GetBitwidth(), increment.IsSigned())) : iter_count; // Overflowing the iteration count. if (loop_iteration_count_->lt(iter_count)) { return false; } loop_bound_ = bound; loop_increment_ = increment; loop_iteration_idx_ = parsed_loop->static_while_loop->induction_var_index; VLOG(1) << "Bound: " << loop_bound_->ToString() << " Start: " << loop_start_->ToString() << " Increment: " << loop_increment_->ToString(); // Simple invariant analysis. Just support arrays in the first nest of the // while() input. if (loop_root->opcode() == HloOpcode::kTuple) { for (int i = 0; i < loop_root->operand_count(); ++i) { if (loop_root->operand(i)->opcode() != HloOpcode::kGetTupleElement) { continue; } if (i != loop_root->operand(i)->tuple_index()) { continue; } invariant_loop_parameters_.insert(loop_root->operand(i)); } } // Extract all loop invariant instructions. ExtractLoopInvariantOps(); return true; } VLOG(1) << "Bound: " << loop_bound_->ToString() void WhileLoopAnalysis::CollectCollectivesToMove( int64_t level_to_operate_on, CollectivePipeliner::PipeliningDirection direction, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate should_allow_loop_variant_parameter_in_chain, bool should_allow_control_dependencies, bool should_add_loop_invariant_op_in_chain) { move_infos_.clear(); HloComputation* while_body = while_->while_body(); const HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; // If the parameter tuple escapes then we can't guarantee that the replacement // for the next iteration is used by everybody unless we create a tuple with // the replacement that would probably limit overlap, so avoid this. if (absl::c_any_of(loop_parameter->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } if (absl::c_any_of(while_->users(), [](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kGetTupleElement; })) { return; } absl::flat_hash_map<int64_t, int64_t> parameter_gtes_count; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement); ++parameter_gtes_count[user->tuple_index()]; } absl::flat_hash_map<const HloInstruction*, Range> index_ranges; absl::flat_hash_map<const HloInstruction*, int64_t> index_per_dyn_update_slice; std::optional<Range> index_range; if (loop_bound_) { // Compute the range of the index as "start + iteration_count * increment" index_range = Range{*loop_start_, loop_start_->add(loop_iteration_count_ ->sub(ConstantValue::GetOne( loop_start_->GetBitwidth(), loop_start_->IsSigned())) .mul(*loop_increment_)), /*is_linear=*/true}; } int64_t count = 0; absl::flat_hash_map<const HloInstruction*, int64_t> instruction_order; for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr->opcode() == HloOpcode::kGetTupleElement) { if (index_range && instr->tuple_index() == 0) { index_ranges.insert({instr, *index_range}); } } instruction_order[instr] = count++; } for (auto* instr : while_body->instructions()) { if (direction == CollectivePipeliner::PipeliningDirection::kForward && (instr->operand_count() != 1 || instr->shape().dimensions_size() != instr->operand(0)->shape().dimensions_size())) { continue; } if (!should_process(instr)) { continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForward || direction == CollectivePipeliner::PipeliningDirection::kForwardSink) { auto [dyn_update, formatting_ops] = CheckStoreIntoSliceIsCompatible( instr, while_body, level_to_operate_on, pipeline_use_tree_, acceptable_formatting); if (dyn_update == nullptr) { VLOG(5) << "Skipping " << instr->ToString() << " because update users > 1 or single user is not the root of " "computation"; continue; } std::optional<int64_t> sliced_dim = GetSlicedDimension(dyn_update); if (!sliced_dim.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find sliced dimension"; continue; } if (direction == CollectivePipeliner::PipeliningDirection::kForwardSink && (*sliced_dim != 0 || dyn_update->shape().dimensions(0) != loop_iteration_count_->GetUnsignedValue())) { VLOG(5) << "Skipping " << instr->name() << " because number of iteration of the loop doesn't match " "slices being inserted or slice dim is not 0. slice_dim = " << *sliced_dim << " loop count = " << loop_iteration_count_->GetUnsignedValue(); } if (!process_different_sized_options_) { if (!formatting_ops.empty()) { if (instr->operand(0)->shape() != formatting_ops.back()->shape()) { continue; } auto dependencies_to_pipeline = CollectDependenciesToPipeline( instr, absl::MakeConstSpan(formatting_ops)); bool skip_because_not_same_size = false; // If any instruction in the dependency chain is not of the same size // then we abort for this instruction. for (auto* dependency : dependencies_to_pipeline) { if (ShapeUtil::IsEffectiveScalar(dependency->shape())) { skip_because_not_same_size = true; break; } } if (skip_because_not_same_size) { continue; } } else if (instr->operand(0)->shape() != instr->shape()) { continue; } } const HloInstruction* to_insert_into = dyn_update->operand(0); if (level_to_operate_on == 0 && (to_insert_into->opcode() != HloOpcode::kGetTupleElement || to_insert_into->operand(0) != loop_parameter)) { VLOG(5) << "Skipping " << instr->name() << " because slice to insert into is not a GTE from input " "parameter " << to_insert_into->ToString(); continue; } if (dyn_update->user_count() != 1) { continue; } // If Level is > 0 then we already did our analysis in the previous // iteration for safeness of this index to transform. if (level_to_operate_on == 0) { if (to_insert_into->opcode() == HloOpcode::kGetTupleElement) { // GTE for this parameter is not CSEd. Abort because we don't analyze // every single use from other GTEs. if (parameter_gtes_count.at(to_insert_into->tuple_index()) != 1) { VLOG(5) << "Skipping " << instr->name() << " because there are multiple parameter GTEs for this slice"; continue; } } HloInstruction* dyn_update_idx = dyn_update->mutable_operand( dyn_update->first_index_operand_number() + *sliced_dim); if (level_to_operate_on == 0 && !CheckParameterUsageIsCompatible(to_insert_into, dyn_update, dyn_update_idx, *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because parameter usage doesn't follow the expected pattern"; continue; } if (!AllIndicesConstantsExceptOne( dyn_update, dyn_update->first_index_operand_number() + *sliced_dim)) { VLOG(5) << "Skipping " << instr->name() << " because update slicing doesn't match expectation"; continue; } if (!CheckIndexIsMonotonic(dyn_update_idx, index_ranges)) { VLOG(5) << "Skipping " << instr->name() << " because update index is not monotonic"; continue; } } std::optional<int64_t> output_idx = FindOutputIndexForDynamicUpdateSlice( dyn_update, while_body->root_instruction()); if (!output_idx.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because couldn't find unique output index for insertion"; continue; } auto merge_as_formatting = [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; auto it = index_per_dyn_update_slice.find(dyn_update); if (it != index_per_dyn_update_slice.end()) { // Merge stuff with existing entry. merge_as_formatting(it, instr, dyn_update, formatting_ops); continue; } index_per_dyn_update_slice[dyn_update] = move_infos_.size(); move_infos_.push_back({instr, dyn_update, std::move(formatting_ops), *sliced_dim, *output_idx}); } else { CHECK_EQ(direction, CollectivePipeliner::PipeliningDirection::kBackward); auto chain_collected = CollectChainsToPushBackwards( instr, *loop_iteration_idx_, while_body, level_to_operate_on, invariant_loop_parameters_, should_allow_loop_variant_parameter_in_chain, should_allow_control_dependencies, invariant_loop_instructions_, should_add_loop_invariant_op_in_chain); if (!chain_collected.has_value()) { VLOG(5) << "Skipping " << instr->name() << " because didn't find compatible slice of parameter"; continue; } move_infos_.push_back( WhileMoveInfo{instr, nullptr, std::move(*chain_collected), -1, -1}); } if (move_infos_.size() >= max_pipelining_per_loop_) { break; } } if (direction != CollectivePipeliner::PipeliningDirection::kForward) { return; } dus_index_map_.clear(); for (auto& to_move : move_infos_) { HloInstruction* dus_index = to_move.dynamic_update_slice->mutable_operand( to_move.dynamic_update_slice->first_index_operand_number() + to_move.sliced_idx); auto it = dus_index_map_.find(dus_index); int64_t dus_index_tuple_position = dus_index_map_.size(); if (it != dus_index_map_.end()) { dus_index_tuple_position = it->second; } else { dus_index_map_[dus_index] = dus_index_tuple_position; } } } VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) VLOG(5) VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() VLOG(5) << "Skipping " << instr->name() [this, &instruction_order]( absl::flat_hash_map<const HloInstruction*, int64_t>::iterator it, HloInstruction* instr, HloInstruction* dyn_upd, absl::Span<HloInstruction* const> formatting_ops) { CHECK_EQ(move_infos_[it->second].dynamic_update_slice, dyn_upd) << "Not the same dynamic-update-slice for converging entry"; absl::flat_hash_set<const HloInstruction*> existing_entry_instrs( move_infos_[it->second].formatting_ops.begin(), move_infos_[it->second].formatting_ops.end()); existing_entry_instrs.insert( move_infos_[it->second].collective_to_move); // If instr is already in the set then this instruction is already // in formatting-ops of the other one, so its already pipelined. if (existing_entry_instrs.count(instr)) { return; } move_infos_[it->second].formatting_ops.push_back(instr); for (auto* op : formatting_ops) { if (!existing_entry_instrs.count(op)) { move_infos_[it->second].formatting_ops.push_back(op); } } absl::c_sort(move_infos_[it->second].formatting_ops, [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); }; [&](const HloInstruction* a, const HloInstruction* b) { return instruction_order[a] < instruction_order[b]; }); VLOG(5) << "Skipping " << instr->name() bool IsLoopInvariant( const HloInstruction* instr, absl::flat_hash_map<const HloInstruction*, bool>& invariant_cache) { auto it = invariant_cache.find(instr); if (it != invariant_cache.end()) { return it->second; } // This performs a post order iteration of the graph. First element is the // current HLO in the stack and the second parameter is the number of operands // to still visit before visiting the HLO itself. std::vector<std::pair<const HloInstruction*, int>> stack( 1, std::make_pair(instr, 0)); absl::flat_hash_set<const HloInstruction*> visited; while (!stack.empty()) { auto& current = stack.back(); invariant_cache[std::get<0>(current)] = true; if (std::get<0>(current)->HasSideEffect() || std::get<0>(current)->opcode() == HloOpcode::kParameter) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } if (std::get<0>(current)->operands().empty()) { invariant_cache[std::get<0>(current)] = true; stack.pop_back(); continue; } if (std::get<1>(current) > 0) { auto* current_operand = std::get<0>(current)->operand(std::get<1>(current) - 1); auto cop_it = invariant_cache.find(current_operand); CHECK(cop_it != invariant_cache.end()) << "Entry expected to be populated"; if (!cop_it->second) { invariant_cache[std::get<0>(current)] = false; stack.pop_back(); continue; } } if (std::get<0>(current)->operand_count() == std::get<1>(current)) { stack.pop_back(); continue; } auto* next_operand = std::get<0>(current)->operand(std::get<1>(current)++); auto op_it = invariant_cache.find(next_operand); if (op_it == invariant_cache.end()) { stack.push_back(std::make_pair(next_operand, 0)); } else if (!op_it->second) { invariant_cache[next_operand] &= op_it->second; } } it = invariant_cache.find(instr); CHECK(it != invariant_cache.end()) << "We should have computed \"instr\" value"; return it->second; } Shape ComputeFullOutputShape(const WhileMoveInfo& move_info, const Shape& base_shape) { return ShapeUtil::PrependMajorDimension( move_info.dynamic_update_slice->operand(0) ->shape() .dimensions()[move_info.sliced_idx], base_shape); } HloInstruction* CreateZero(HloComputation* comp, const Shape& shape, PrimitiveType ptype) { if (shape.dimensions_size() == 0) { return comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))); } HloInstruction* zero_constant = comp->AddInstruction(HloInstruction::CreateBroadcast( shape, comp->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(ptype))), {})); return zero_constant; } absl::StatusOr<std::vector<Interval>> ParseVectorOfPairs( absl::string_view str) { TF_ASSIGN_OR_RETURN(std::vector<ReplicaGroup> replica_groups, ParseReplicaGroupsOnly(str)); std::vector<Interval> res; res.reserve(replica_groups.size()); for (const ReplicaGroup& replica_group : replica_groups) { TF_RET_CHECK(replica_group.replica_ids_size() == 2); int64_t a = replica_group.replica_ids(0); int64_t b = replica_group.replica_ids(1); res.emplace_back(a, b); } return res; } absl::Status UpdateSendRecvValidation( HloInstruction* instruction, bool is_peeled, CollectivePipeliner::PipeliningDirection direction, const WhileLoopAnalysis& loop_analysis) { if (instruction->opcode() != HloOpcode::kCollectivePermute) { return absl::OkStatus(); } const auto& frontend_attributes = instruction->frontend_attributes().map(); if (!frontend_attributes.contains(kSendRecvValidationAttr)) { return absl::OkStatus(); } VLOG(3) << "Trip count = " << loop_analysis.GetLoopIterationCount()->GetSignedValue(); VLOG(3) << "Collective permute with _xla_send_recv_validation: " << instruction->ToString(); TF_ASSIGN_OR_RETURN( Intervals old_intervals, ParseVectorOfPairs(frontend_attributes.at(kSendRecvValidationAttr))); Intervals intervals; if (direction == CollectivePipeliner::kForward) { // It is a forward pipelining which means that the peeled collective permute // is before the loop. It should run once for the devices executing the // first iteration and the internal collective permute now sees each // original iteration decreased by one. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=0<=b, {1,0} otherwise} // internal collective permute: {{max(0, a-1), max(0, b-1)} | {a,b} in old} for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= 0 && 0 <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({std::max(0l, a - 1), std::max(0l, b - 1)}); } } } else if (direction == CollectivePipeliner::kBackward) { // It is a backward pipelining which means that the peeled collective is // after the loop. It should run once for the devices executing the last // iteration and the internal collective permute doesn't see the last // iteration. // // peeled collective permute: // {{0,0} if {a,b} in old and a<=n<=b where n=#last_iteration, {1,0} // otherwise} // interval collective permute: // {{a,min(n-1,b)} | {a,b} in old and n=#last_iteration} auto trip_count_value = loop_analysis.GetLoopIterationCount(); if (!trip_count_value) { return absl::InternalError( "Unable to deduce loop trip count in collective pipeliner. This is " "required for backward pipelining while fixing the " "_xla_send_recv_validation attribute"); } int64_t trip_count = trip_count_value->GetSignedValue(); int64_t last_iteration = trip_count - 1; for (auto [a, b] : old_intervals) { if (is_peeled) { if (a <= last_iteration && last_iteration <= b) { intervals.push_back({0, 0}); } else { intervals.push_back({1, 0}); } } else { intervals.push_back({a, std::min(last_iteration - 1, b)}); } } } hlo_instruction_utils::AddOrUpdateVectorOfPairsAsAttribute( instruction, kSendRecvValidationAttr, intervals); VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " << instruction->ToString(); return absl::OkStatus(); } VLOG(3) << "Trip count = " VLOG(3) << "Collective permute with _xla_send_recv_validation: " VLOG(3) << "Updated collective_permute with _xla_send_recv_validation: " absl::Status TransformLoopForward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, HloPredicate reuse_output_buffer, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. InstructionMap while_body_to_peeled; absl::flat_hash_set<HloInstruction*> to_skip_set; absl::flat_hash_map<HloInstruction*, HloInstruction*> formatting_map; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; std::vector<int64_t> moves_requiring_special_output; int64_t count = 0; // Add all-reduces to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { to_skip_set.insert(to_move.collective_to_move); if (!to_move.formatting_ops.empty()) { formatting_map[to_move.formatting_ops.back()] = to_move.collective_to_move; } const Shape& output_shape = to_move.formatting_ops.empty() ? to_move.collective_to_move->shape() : to_move.formatting_ops.back()->shape(); if (!reuse_output_buffer(to_move.collective_to_move) || output_shape != to_move.collective_to_move->operand(0)->shape()) { moves_requiring_special_output.push_back(count); to_skip_set.insert(to_move.dynamic_update_slice); } ++count; } // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); const int64_t initial_inputs = loop_init->operand_count(); while_body_to_peeled[loop_parameter] = loop_init; for (auto* user : loop_parameter->users()) { CHECK_EQ(user->opcode(), HloOpcode::kGetTupleElement) << "Expected only get-tuple-elements as users"; while_body_to_peeled[user] = loop_init->mutable_operand(user->tuple_index()); } CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; const int64_t operands_indices_count = loop_init->operand_count() + loop_analysis.GetUniqueDUSIndices(); const int64_t new_loop_tuple_operand_count = operands_indices_count + moves_requiring_special_output.size(); new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = loop_init->mutable_operand(i); } // Duplicate the loop body into the loop parent computation, so that the first // iteration happens there. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter) { continue; } if (ContainsKey(to_skip_set, instr)) { auto it = while_body_to_peeled.find(instr->operand(0)); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } auto formatting_it = formatting_map.find(instr); if (formatting_it != formatting_map.end()) { auto it = while_body_to_peeled.find(formatting_it->second); CHECK(it != while_body_to_peeled.end()); HloInstruction* passthrough_operand = it->second; while_body_to_peeled[instr] = passthrough_operand; continue; } std::vector<HloInstruction*> new_operands = MapNewOperands(instr->operands(), while_body_to_peeled); HloInstruction* cloned_instr = loop_computation->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR( UpdateControlDependencies(instr, cloned_instr, while_body_to_peeled)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); while_body_to_peeled[instr] = cloned_instr; auto output_it = is_output_instruction.find(instr); if (output_it != is_output_instruction.end()) { new_init_operands[output_it->second] = cloned_instr; } } // Add indices to access the slices for the previous iteration to the // loop state. Indices used multiple times for multiple slices have been // deduped. for (auto& dus : loop_analysis.GetDUSIndices()) { new_parameter_shapes[dus.second + initial_inputs] = dus.first->shape(); new_root_operands[dus.second + initial_inputs] = dus.first; new_init_operands[dus.second + initial_inputs] = while_body_to_peeled[dus.first]; } absl::flat_hash_map<int64_t, int64_t> moves_requiring_special_output_to_idx; for (int i = 0; i < moves_requiring_special_output.size(); ++i) { HloInstruction* collective = loop_analysis.GetMoveInfos()[moves_requiring_special_output[i]] .collective_to_move; moves_requiring_special_output_to_idx[moves_requiring_special_output[i]] = operands_indices_count + i; new_parameter_shapes[operands_indices_count + i] = collective->operand(0)->shape(); new_root_operands[operands_indices_count + i] = collective->mutable_operand(0); new_init_operands[operands_indices_count + i] = while_body_to_peeled[collective->mutable_operand(0)]; } for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { is_output_instruction[pipelined] = new_init_operands.size(); new_parameter_shapes.push_back(pipelined->shape()); new_root_operands.push_back(pipelined); new_init_operands.push_back(while_body_to_peeled[pipelined]); } } // Clone new loop computations (cond and body) and create the new loop // instruction and connect it to the users/operands of the old loop. Shape loop_state_shape = ShapeUtil::MakeTupleShape(new_parameter_shapes); absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; InstructionMap pipelined_values_map_inloop; InstructionMap pipelined_values_map_outloop; replacements[loop_parameter] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_param"); replacements[while_loop->while_condition()->parameter_instructions()[0]] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "loop_peel_cond_param"); replacements[while_body->root_instruction()] = HloInstruction::CreateTuple(new_root_operands); HloComputation* new_while_condition = loop_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); HloComputation* new_while_body = loop_computation->parent()->AddEmbeddedComputation( while_body->CloneWithReplacements(&replacements)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kForward, loop_analysis)); } HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); while_body_to_peeled[while_body->root_instruction()] = new_init; TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_init, while_body_to_peeled)); HloInstruction* new_while_loop = loop_computation->AddInstruction(HloInstruction::CreateWhile( loop_state_shape, new_while_condition, new_while_body, new_init)); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(new_while_loop)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); // Run WhileLoopAnalysis again on the new loop to collect the position of the // all-reduces in the new cloned loop as they aren't the same of the old. // Loop analysis should result exactly the same, because the loop is the same // except some new scalar unused parameters added at the end. WhileLoopAnalysis new_loop_analysis( new_while_loop, loop_analysis.GetMaxPipeliningPerLoop(), pipeline_use_tree, process_different_sized_ops, loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement())); new_loop_analysis.ComputeLoopStatistics(); new_loop_analysis.CollectCollectivesToMove( level_to_operate_on, CollectivePipeliner::PipeliningDirection::kForward, should_process, acceptable_formatting); CHECK_EQ(new_loop_analysis.GetMoveInfos().size(), loop_analysis.GetMoveInfos().size()); for (int64_t i = new_loop_tuple_operand_count; i < new_parameter_shapes.size(); ++i) { HloInstruction* pipelined_value_load_inloop = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( new_while_body->parameter_instruction(0), i)); HloInstruction* pipelined_value_load_outloop = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, i)); pipelined_values_map_inloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_inloop; pipelined_values_map_outloop[new_while_body->root_instruction()->operand( i)] = pipelined_value_load_outloop; } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; auto process_slice = [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; auto extract_and_process_slice = [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; for (int i = 0; i < new_loop_analysis.GetMoveInfos().size(); ++i) { auto& move_info = new_loop_analysis.GetMoveInfos()[i]; std::vector<HloInstruction*> loop_output_to_replace; HloInstruction* parameter_instr = new_while_body->parameter_instructions()[0]; for (auto* user : new_while_loop->users()) { if (user->tuple_index() != move_info.output_idx) { continue; } loop_output_to_replace.push_back(user); } const HloInstruction* dus_index_curr_iteration = move_info.dynamic_update_slice->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx); const int64_t offset_for_index = new_loop_analysis.GetDUSIndex(dus_index_curr_iteration) + initial_inputs; Shape index_shape = dus_index_curr_iteration->shape(); HloInstruction* input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, parameter_instr, offset_for_index)); if (insert_non_alias_custom_call) { HloInstruction* level = new_while_body->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); input_dus_idx = new_while_body->AddInstruction(HloInstruction::CreateCustomCall( index_shape, {input_dus_idx, level}, CollectivePipeliner::kInsertedByPreviousStep)); } HloInstruction* output_dus_idx = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( index_shape, new_while_loop, offset_for_index)); HloInstruction* input_stacked_data = move_info.dynamic_update_slice->mutable_operand(0); HloInstruction* output_stacked_data = loop_computation->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.dynamic_update_slice->shape(), new_while_loop, move_info.output_idx)); HloInstruction* input_data_to_slice = input_stacked_data; HloInstruction* output_data_to_slice = output_stacked_data; auto it = moves_requiring_special_output_to_idx.find(i); if (it != moves_requiring_special_output_to_idx.end()) { input_data_to_slice = new_while_body->AddInstruction(HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), parameter_instr, it->second)); output_data_to_slice = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement( move_info.collective_to_move->operand(0)->shape(), new_while_loop, it->second)); } TF_ASSIGN_OR_RETURN(input_stacked_data, extract_and_process_slice( input_stacked_data, input_data_to_slice, move_info, pipelined_values_map_inloop, input_dus_idx)); TF_ASSIGN_OR_RETURN( output_stacked_data, extract_and_process_slice(output_stacked_data, output_data_to_slice, move_info, pipelined_values_map_outloop, output_dus_idx)); auto replace_instructions_with = [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; auto* new_peeled_dus = input_stacked_data; if (it == moves_requiring_special_output_to_idx.end()) { new_peeled_dus = insert_slice( move_info.collective_to_move->mutable_operand(0), move_info.sliced_idx, move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), move_info.dynamic_update_slice->mutable_operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx), input_stacked_data); } TF_RETURN_IF_ERROR( move_info.dynamic_update_slice->ReplaceAllUsesWith(new_peeled_dus)); TF_RETURN_IF_ERROR(new_while_body->RemoveInstructionAndUnusedOperands( move_info.dynamic_update_slice)); TF_RETURN_IF_ERROR(replace_instructions_with( absl::MakeSpan(loop_output_to_replace), output_stacked_data)); } TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto insert_slice = [](HloInstruction* to_insert, int64_t index_position, int64_t num_indices, HloInstruction* dus_index, HloInstruction* base) { HloComputation* computation = to_insert->parent(); HloInstruction* zero = computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(dus_index->shape().element_type()))); std::vector<HloInstruction*> indices(num_indices, zero); indices[index_position] = dus_index; return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( base->shape(), base, to_insert, indices)); }; [&next_channel_id, insert_non_alias_custom_call, level_to_operate_on]( HloInstruction* stacked_data, const InstructionMap& pipelined_values_map, const WhileMoveInfo& move_info) -> absl::StatusOr<HloInstruction*> { HloInstruction* processed = stacked_data->parent()->AddInstruction( move_info.collective_to_move->CloneWithNewOperands( move_info.collective_to_move->shape(), {stacked_data})); UpdateInstructionChannelId(processed, next_channel_id); if (insert_non_alias_custom_call) { HloInstruction* level = stacked_data->parent()->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0(level_to_operate_on + 1))); processed = stacked_data->parent()->AddInstruction( HloInstruction::CreateCustomCall( processed->shape(), {processed, level}, CollectivePipeliner::kInsertedByPreviousStep)); } InstructionMap cloned_map = pipelined_values_map; cloned_map[move_info.collective_to_move] = processed; for (auto* formatting_op : move_info.formatting_ops) { auto new_operands = MapNewOperands(formatting_op->operands(), cloned_map); processed = stacked_data->parent()->AddInstruction( formatting_op->CloneWithNewOperands(formatting_op->shape(), new_operands)); cloned_map[formatting_op] = processed; } return processed; }; [&process_slice]( HloInstruction* stacked_data, HloInstruction* data_to_slice, const WhileMoveInfo& move_info, const InstructionMap& pipelined_values_map, HloInstruction* dus_index) -> absl::StatusOr<HloInstruction*> { HloComputation* computation = stacked_data->parent(); const Shape& slice_target_shape = move_info.collective_to_move->operand(0)->shape(); HloInstruction* sliced_data = data_to_slice; PrimitiveType element_type = move_info.dynamic_update_slice ->operand( move_info.dynamic_update_slice->first_index_operand_number() + move_info.sliced_idx) ->shape() .element_type(); HloInstruction* zero = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero(element_type))); std::vector<HloInstruction*> indices( move_info.dynamic_update_slice->operand_count() - move_info.dynamic_update_slice->first_index_operand_number(), zero); indices[move_info.sliced_idx] = dus_index; if (slice_target_shape != data_to_slice->shape()) { // Slice matrix. absl::InlinedVector<int64_t, 4> dynamic_slice_sizes; dynamic_slice_sizes.reserve(slice_target_shape.dimensions_size()); for (int i = 0; i < slice_target_shape.dimensions_size(); ++i) { dynamic_slice_sizes.push_back(slice_target_shape.dimensions(i)); } sliced_data = computation->AddInstruction(HloInstruction::CreateDynamicSlice( slice_target_shape, data_to_slice, indices, dynamic_slice_sizes)); } TF_ASSIGN_OR_RETURN( sliced_data, process_slice(sliced_data, pipelined_values_map, move_info)); return computation->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( move_info.dynamic_update_slice->shape(), stacked_data, sliced_data, indices)); }; [](absl::Span<HloInstruction*> to_replace_instrs, HloInstruction* new_instr) { for (auto* to_replace : to_replace_instrs) { HloComputation* computation = to_replace->parent(); TF_RETURN_IF_ERROR(to_replace->ReplaceAllUsesWith(new_instr)); TF_RETURN_IF_ERROR( computation->RemoveInstructionAndUnusedOperands(to_replace)); } return absl::OkStatus(); }; absl::Status TransformLoopForwardSink(const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool pipeline_use_tree, bool process_different_sized_ops, HloPredicate should_process, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_map<const HloInstruction*, bool> invariant_cache; // Map get-tuple-elements() inside of the loop with elements passed to the // tuple that is the "init" of the loop. HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_init = while_loop->mutable_operand(0); CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. HloComputation* loop_computation = while_loop->parent(); HloComputation* body_computation = while_loop->while_body(); std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; absl::flat_hash_set<int64_t> indices_to_insert; const int64_t operands_indices_count = loop_init->operand_count(); const int64_t new_loop_tuple_operand_count = operands_indices_count; absl::flat_hash_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; new_parameter_shapes.resize(new_loop_tuple_operand_count); new_root_operands.resize(new_loop_tuple_operand_count); new_init_operands.resize(new_loop_tuple_operand_count); absl::flat_hash_set<int64_t> original_to_move_indices; // Initialize data structures with information about the outputs that need to // be sunk. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* collective = to_move.collective_to_move; Shape shape = ComputeFullOutputShape(to_move, collective->operand(0)->shape()); new_init_operands[to_move.output_idx] = CreateZero(loop_computation, shape, shape.element_type()); new_parameter_shapes[to_move.output_idx] = shape; original_to_move_indices.insert(to_move.output_idx); indices_to_insert.insert(to_move.output_idx); new_root_operands[to_move.output_idx] = collective->mutable_operand(0); } // Initialize the data structures for output indices that aren't modified. for (int i = 0; i < loop_parameter->shape().tuple_shapes().size(); ++i) { if (original_to_move_indices.contains(i)) { continue; } new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_init_operands[i] = loop_init->mutable_operand(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); } // Collect instructions that are necessary for the execution of the sunk // instructions. If they are loop invariant they are stored as is, otherwise // the version for each iteration is accumulated in a buffer. for (auto& move_info : loop_analysis.GetMoveInfos()) { auto pipelined_instrs = CollectDependenciesToPipeline( move_info.collective_to_move, absl::MakeSpan(move_info.formatting_ops)); for (auto* pipelined : pipelined_instrs) { if (pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(pipelined, invariant_cache); is_output_instruction[pipelined] = new_init_operands.size(); if (is_loop_invariant) { new_parameter_shapes.push_back(pipelined->shape()); new_init_operands.push_back( CreateZero(loop_computation, pipelined->shape(), pipelined->shape().element_type())); new_root_operands.push_back(pipelined); continue; } Shape expanded_shape = ComputeFullOutputShape(move_info, pipelined->shape()); new_parameter_shapes.push_back(expanded_shape); new_init_operands.push_back(CreateZero(loop_computation, expanded_shape, expanded_shape.element_type())); indices_to_insert.insert(new_root_operands.size()); Shape extra_trivial_dim_shape = ShapeUtil::PrependMajorDimension(1, pipelined->shape()); HloInstruction* reshaped = body_computation->AddInstruction( HloInstruction::CreateReshape(extra_trivial_dim_shape, pipelined)); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero(body_computation, move_info.dynamic_update_slice->index_shapes()[0], move_info.dynamic_update_slice->index_shapes()[0] .element_type())); indices[0] = move_info.dynamic_update_slice->index_operands()[0]; HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)new_root_operands.size())))}, "PlaceHolder")); reshaped = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, reshaped, indices)); new_root_operands.push_back(reshaped); } } std::unique_ptr<HloInstruction> new_parameter = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat("sink_", loop_parameter->name())); // Insert inputs to the collective we are sinking in slices for the loop. for (auto& to_move : loop_analysis.GetMoveInfos()) { if (!indices_to_insert.contains(to_move.output_idx)) { continue; } HloInstruction* to_insert = body_computation->AddInstruction(HloInstruction::CreateReshape( ShapeUtil::PrependMajorDimension( 1, new_root_operands[to_move.output_idx]->shape()), new_root_operands[to_move.output_idx])); Shape expanded_shape = ComputeFullOutputShape( to_move, new_root_operands[to_move.output_idx]->shape()); HloInstruction* input = body_computation->AddInstruction(HloInstruction::CreateCustomCall( expanded_shape, {body_computation->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR0((int32_t)to_move.output_idx)))}, "PlaceHolder")); std::vector<HloInstruction*> indices( expanded_shape.dimensions_size(), CreateZero( body_computation, to_move.dynamic_update_slice->index_shapes()[0], to_move.dynamic_update_slice->index_shapes()[0].element_type())); indices[0] = to_move.dynamic_update_slice->index_operands()[0]; to_insert = body_computation->AddInstruction( HloInstruction::CreateDynamicUpdateSlice(expanded_shape, input, to_insert, indices)); new_root_operands[to_move.output_idx] = to_insert; } std::unique_ptr<HloInstruction> new_root_instr = HloInstruction::CreateTuple(new_root_operands); // Mark for removal (by setting replacement entry to nullptr) the users of the // old parameters we are replacing for the loops. All the computation tree // for those should be not used in the new loop. for (auto* p_user : body_computation->parameter_instructions()[0]->users()) { CHECK_EQ(p_user->opcode(), HloOpcode::kGetTupleElement); const int64_t tuple_idx = p_user->tuple_index(); if (!indices_to_insert.contains(tuple_idx)) { continue; } replacements[p_user] = HloInstruction::CreateGetTupleElement(new_parameter.get(), tuple_idx); std::vector<HloInstruction*> stack(p_user->users().begin(), p_user->users().end()); while (!stack.empty()) { auto* u = stack.back(); stack.pop_back(); replacements[u] = nullptr; for (auto* user : u->users()) { if (user == body_computation->root_instruction()) { continue; } stack.push_back(user); } } } replacements[body_computation->parameter_instruction(0)] = std::move(new_parameter); replacements[body_computation->root_instruction()] = std::move(new_root_instr); replacements[while_loop->while_condition()->parameter_instruction(0)] = HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), absl::StrCat( "sink_", while_loop->while_condition()->parameter_instruction(0)->name())); // Clone and create new loop. HloInstruction* new_init = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); HloComputation* cloned_body = body_computation->parent()->AddEmbeddedComputation( body_computation->CloneWithReplacements(&replacements)); HloComputation* cloned_cond = body_computation->parent()->AddEmbeddedComputation( while_loop->while_condition()->CloneWithReplacements(&replacements)); for (int64_t i = 0; i < cloned_body->root_instruction()->operand_count(); ++i) { HloInstruction* output = cloned_body->root_instruction()->mutable_operand(i); if (output->opcode() != HloOpcode::kDynamicUpdateSlice) { continue; } if (!output->operand(0)->IsCustomCall("PlaceHolder")) { continue; } auto idx = Cast<HloConstantInstruction>(output->operand(0)->operand(0)) ->literal() .GetFirstInteger(); auto* new_param = cloned_body->AddInstruction(HloInstruction::CreateGetTupleElement( output->shape(), cloned_body->parameter_instruction(0), *idx)); HloInstruction* old_operand_param = output->mutable_operand(0); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, new_param)); TF_RETURN_IF_ERROR( old_operand_param->parent()->RemoveInstruction(old_operand_param)); if (insert_non_alias_custom_call && original_to_move_indices.contains(i)) { auto* old_operand = output->mutable_operand(1); auto* custom_call = cloned_body->AddInstruction(HloInstruction::CreateCustomCall( old_operand->shape(), {old_operand}, /*custom_call_target=*/CollectivePipeliner::kSunkByPreviousStep)); TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, custom_call)); } } HloInstruction* new_while = loop_computation->AddInstruction(HloInstruction::CreateWhile( new_init->shape(), cloned_cond, cloned_body, new_init)); std::vector<HloInstruction*> new_output_tuple; new_output_tuple.resize(new_root_operands.size(), nullptr); // Reproduce computation to the output after the loop on the full shape. for (auto& to_move : loop_analysis.GetMoveInfos()) { InstructionMap pipelined_map; HloInstruction* to_sink = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, to_move.output_idx)); const int64_t new_dim_limit = to_move.dynamic_update_slice->shape().dimensions(0); pipelined_map[to_move.collective_to_move->mutable_operand(0)] = to_sink; auto pipelined_instrs = CollectDependenciesToPipeline( to_move.collective_to_move, absl::MakeSpan(to_move.formatting_ops)); for (auto* original_pipelined : pipelined_instrs) { if (original_pipelined->opcode() == HloOpcode::kConstant) { continue; } const bool is_loop_invariant = IsLoopInvariant(original_pipelined, invariant_cache); CHECK(is_output_instruction.contains(original_pipelined)); int64_t pipelined_idx = is_output_instruction[original_pipelined]; HloInstruction* pipelined = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, pipelined_idx)); // Broadcast loop invariant instructions. if (is_loop_invariant) { Shape full_shape = ComputeFullOutputShape(to_move, pipelined->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(pipelined->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, pipelined, operand_dims)); pipelined_map[original_pipelined] = broadcasted; } else { pipelined_map[original_pipelined] = pipelined; } } // Cloning the main instruction HloInstruction* pipelined_instr_cloned = loop_computation->AddInstruction( to_move.collective_to_move->CloneWithNewOperands( ComputeFullOutputShape(to_move, to_move.collective_to_move->shape()), {to_sink})); UpdateInstructionChannelId(pipelined_instr_cloned, next_channel_id); pipelined_map[to_move.collective_to_move] = pipelined_instr_cloned; absl::flat_hash_set<HloInstruction*> to_add_batch_set; auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; absl::flat_hash_set<HloInstruction*> formatting_ops_set( to_move.formatting_ops.begin(), to_move.formatting_ops.end()); std::vector<HloInstruction*> stack(1, to_move.collective_to_move); for (auto* current : to_move.formatting_ops) { if (IsLoopInvariant(current, invariant_cache)) { continue; } to_add_batch_set.insert(current); } // We are adding a batch dimension to the formatting ops, so we need to // specially rewrite each instruction potentially if adding dimensions has // an effect on the instruction itself (like say broadcast, slices ... // etc). for (HloInstruction* formatting_op : to_move.formatting_ops) { if (!to_add_batch_set.contains(formatting_op) && formatting_op->opcode() != HloOpcode::kBroadcast) { HloInstruction* cloned_not_to_batch = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( formatting_op->shape(), collect_operands(formatting_op))); UpdateInstructionChannelId(cloned_not_to_batch, next_channel_id); pipelined_map[formatting_op] = cloned_not_to_batch; continue; } if (formatting_op->IsElementwise() || formatting_op->opcode() == HloOpcode::kReshape || formatting_op->opcode() == HloOpcode::kAllReduce || formatting_op->opcode() == HloOpcode::kConvert || formatting_op->opcode() == HloOpcode::kCollectivePermute) { HloInstruction* cloned_elementwise = loop_computation->AddInstruction( formatting_op->CloneWithNewOperands( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op))); pipelined_map[formatting_op] = cloned_elementwise; continue; } if (formatting_op->opcode() == HloOpcode::kReduce) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(formatting_op->dimensions().begin(), formatting_op->dimensions().end()); for (auto& dim : dimensions) { ++dim; } // Look through broadcast for reduce init value. if (operands[1]->opcode() == HloOpcode::kBroadcast) { CHECK(operands[1]->operand(0)->opcode() == HloOpcode::kConstant); operands[1] = operands[1]->mutable_operand(0); } HloInstruction* expanded_reduce = loop_computation->AddInstruction(HloInstruction::CreateReduce( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], operands[1], dimensions, formatting_op->to_apply())); pipelined_map[formatting_op] = expanded_reduce; continue; } if (formatting_op->opcode() == HloOpcode::kBroadcast) { auto operands = collect_operands(formatting_op); std::vector<int64_t> dimensions(1, 0); for (const int64_t dim : formatting_op->dimensions()) { dimensions.push_back(dim + 1); } // Constant scalars don't get expanded ahead of time and are kept // scalar. if (operands[0]->shape().dimensions_size() == 0) { dimensions.clear(); } HloInstruction* expanded_broadcast = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( ComputeFullOutputShape(to_move, formatting_op->shape()), operands[0], dimensions)); pipelined_map[formatting_op] = expanded_broadcast; continue; } if (formatting_op->opcode() == HloOpcode::kSlice) { std::vector<int64_t> slice_start = formatting_op->slice_starts(); std::vector<int64_t> slice_limits = formatting_op->slice_limits(); std::vector<int64_t> slice_strides = formatting_op->slice_strides(); slice_start.insert(slice_start.begin(), 0); slice_limits.insert(slice_limits.begin(), new_dim_limit); slice_strides.insert(slice_strides.begin(), 1); HloInstruction* expanded_slice = loop_computation->AddInstruction(HloInstruction::CreateSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], slice_start, slice_limits, slice_strides)); pipelined_map[formatting_op] = expanded_slice; continue; } if (formatting_op->opcode() == HloOpcode::kDynamicSlice) { std::vector<int64_t> dynamic_slice_sizes = formatting_op->dynamic_slice_sizes(); dynamic_slice_sizes.insert(dynamic_slice_sizes.begin(), new_dim_limit); HloDynamicSliceInstruction* dynslice = Cast<HloDynamicSliceInstruction>(formatting_op); HloInstruction* zero = loop_computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::Zero( formatting_op->operand(dynslice->first_index_operand_number()) ->shape() .element_type()))); std::vector<HloInstruction*> indices(1, zero); auto collected_operands = collect_operands(formatting_op); indices.insert(indices.end(), std::next(collected_operands.begin()), collected_operands.end()); HloInstruction* expanded_dynslice = loop_computation->AddInstruction(HloInstruction::CreateDynamicSlice( ComputeFullOutputShape(to_move, formatting_op->shape()), collected_operands[0], indices, dynamic_slice_sizes)); pipelined_map[formatting_op] = expanded_dynslice; continue; } if (formatting_op->opcode() == HloOpcode::kPad) { HloPadInstruction* pad_instruction = Cast<HloPadInstruction>(formatting_op); PaddingConfig p_config = pad_instruction->padding_config(); PaddingConfig new_p_config; new_p_config.add_dimensions(); for (auto& dim : p_config.dimensions()) { auto* new_dim = new_p_config.add_dimensions(); *new_dim = dim; } auto new_operands = collect_operands(formatting_op); HloInstruction* expanded_pad = loop_computation->AddInstruction(HloInstruction::CreatePad( ComputeFullOutputShape(to_move, formatting_op->shape()), new_operands[0], new_operands[1], new_p_config)); pipelined_map[formatting_op] = expanded_pad; continue; } if (formatting_op->opcode() == HloOpcode::kTranspose) { HloTransposeInstruction* transpose_instruction = Cast<HloTransposeInstruction>(formatting_op); std::vector<int64_t> new_dims( transpose_instruction->dimensions().begin(), transpose_instruction->dimensions().end()); new_dims.insert(new_dims.begin(), 0); for (int64_t& dim : new_dims) { ++dim; } HloInstruction* expanded_transpose = loop_computation->AddInstruction(HloInstruction::CreateTranspose( ComputeFullOutputShape(to_move, formatting_op->shape()), collect_operands(formatting_op)[0], new_dims)); pipelined_map[formatting_op] = expanded_transpose; continue; } CHECK(false) << "Unsupported instruction " << formatting_op->ToString(); } HloInstruction* inserted_operand = to_move.dynamic_update_slice->mutable_operand(1); CHECK(pipelined_map.contains(inserted_operand)) << "Expected to be processed"; HloInstruction* expanded_inserted = pipelined_map[inserted_operand]; if (!ShapeUtil::Compatible(expanded_inserted->shape(), to_move.dynamic_update_slice->shape())) { expanded_inserted = loop_computation->AddInstruction(HloInstruction::CreateReshape( to_move.dynamic_update_slice->shape(), expanded_inserted)); } new_output_tuple[to_move.output_idx] = expanded_inserted; } // Create new loop tuple replacement. for (int i = 0; i < new_while->shape().tuple_shapes_size(); ++i) { if (new_output_tuple[i] != nullptr) { continue; } new_output_tuple[i] = loop_computation->AddInstruction( HloInstruction::CreateGetTupleElement(new_while, i)); } HloInstruction* new_tuple = loop_computation->AddInstruction( HloInstruction::CreateTuple(new_output_tuple)); TF_RETURN_IF_ERROR(while_loop->ReplaceAllUsesWithDifferentShape(new_tuple)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } auto collect_operands = [&pipelined_map, &to_add_batch_set, loop_computation, &to_move](HloInstruction* instr) { std::vector<HloInstruction*> operands; for (auto* operand : instr->mutable_operands()) { if (operand->opcode() == HloOpcode::kConstant) { HloInstruction* cloned_constant = loop_computation->AddInstruction( operand->CloneWithNewOperands(operand->shape(), {})); if (!to_add_batch_set.contains(instr)) { operands.push_back(cloned_constant); continue; } Shape full_shape = ComputeFullOutputShape(to_move, cloned_constant->shape()); absl::InlinedVector<int64_t, 4> operand_dims; operand_dims.resize(cloned_constant->shape().dimensions_size()); absl::c_iota(operand_dims, 1); HloInstruction* broadcasted = loop_computation->AddInstruction(HloInstruction::CreateBroadcast( full_shape, cloned_constant, operand_dims)); operands.push_back(broadcasted); continue; } auto it = pipelined_map.find(operand); CHECK(it != pipelined_map.end()); operands.push_back(it->second); } return operands; }; static absl::Status TransformLoopBackward( const WhileLoopAnalysis& loop_analysis, bool insert_non_alias_custom_call, int64_t level_to_operate_on, bool process_different_sized_ops, HloPredicate should_process, HloPredicate acceptable_formatting, CollectivePipeliner::HloPostprocessor postprocess_peeled, CollectivePipeliner::HloPostprocessor postprocess_rotated, int64_t& next_channel_id) { // Defining some maps/sets to keep track of instructions duplicated. absl::flat_hash_map<HloInstruction*, HloInstruction*> while_body_to_peeled; absl::flat_hash_map<HloInstruction*, int64_t> collective_to_move_map; absl::flat_hash_set<HloInstruction*> is_pipelined_instruction; absl::flat_hash_map<HloInstruction*, int64_t> is_output_instruction; absl::flat_hash_set<const HloInstruction*> sideeffect_unused_instructions; int64_t count = 0; // Add instructions to duplicate into a set. for (auto& to_move : loop_analysis.GetMoveInfos()) { HloInstruction* instr = to_move.collective_to_move; collective_to_move_map[instr] = count; is_pipelined_instruction.insert(instr); is_pipelined_instruction.insert(to_move.formatting_ops.begin(), to_move.formatting_ops.end()); ++count; // Collect unused instructions with side-effect in the chain, so that we // can skip cloning such instructions. This is to work around the fact that // we can't have unused Recv instructions to avoid deadlock, and // HloModule::RemoveUnusedComputations can't remove unused Recv instructions // as they are tagged as has-side-effect. The operand_count check here // assumes we only need to collect such instructions when pipelining // Recv-done, which may be changed though. if (instr->operand_count() == 1) { const HloInstruction* opnd = instr->operand(0); if (opnd->HasSideEffect() && opnd->user_count() == 1) { sideeffect_unused_instructions.insert(opnd); } } } HloInstruction* while_loop = loop_analysis.while_loop_instruction(); HloComputation* while_body = while_loop->while_body(); CHECK_EQ(while_body->parameter_instructions().size(), 1) << "Expected only one parameter"; HloInstruction* loop_parameter = while_body->parameter_instructions()[0]; HloInstruction* loop_initial_iteration_idx = while_loop->mutable_operand(0)->mutable_operand( *loop_analysis.GetLoopIterationIdx()); // Map loop_parameter to the input tuple for peeling backward. while_body_to_peeled[loop_parameter] = while_loop; CHECK_EQ(while_body->root_instruction()->opcode(), HloOpcode::kTuple); // Record instructions that are part of the output of the loop. for (int i = 0; i < while_body->root_instruction()->operand_count(); ++i) { is_output_instruction[while_body->root_instruction()->mutable_operand(i)] = i; } // Collect the new parameter shapes with the additional state for the indices // and construct new operand vectors for the init of the new loop and its root // instruction. std::vector<HloInstruction*> new_init_operands; std::vector<Shape> new_parameter_shapes; std::vector<HloInstruction*> new_root_operands; // Number of tuple elements is all the original inputs/outputs to the loop + // the pipelined values + the previous iteration loop iteration, which is the // only dynamic thing that is allowed to be used by the computation pipelined // in the previous iteration. const int64_t operands_indices_count = while_loop->shape().tuple_shapes_size() + loop_analysis.GetMoveInfos().size() + 1; new_parameter_shapes.resize(operands_indices_count); new_root_operands.resize(operands_indices_count); new_init_operands.resize(operands_indices_count); // Fill up root and init operands for the new loop. for (int i = 0; i < loop_parameter->shape().tuple_shapes_size(); ++i) { new_parameter_shapes[i] = loop_parameter->shape().tuple_shapes(i); new_root_operands[i] = while_body->root_instruction()->mutable_operand(i); new_init_operands[i] = while_loop->mutable_operand(0)->mutable_operand(i); } // Populating map for cloned instructions in chains pushed backwards. // We need a different map, because we want to map the loop iterator // differently from the rest of the loop. The whole chain is copied // completely, so we don't share anything with the rest of the loop except // parameter. InstructionMap chain_clone_map; chain_clone_map[loop_parameter] = while_loop->mutable_operand(0); for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { chain_clone_map[u] = loop_initial_iteration_idx; } } // Add to the rewritten loop the new parameter/output data that is going to be // pipelined. Clone chains of pipelined data in the parent computation in the // process (they will endup being executed before the loop). for (int i = 0; i < loop_analysis.GetMoveInfos().size(); ++i) { const int64_t idx = i + loop_parameter->shape().tuple_shapes_size(); new_parameter_shapes[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move->shape(); new_root_operands[idx] = loop_analysis.GetMoveInfos()[i].collective_to_move; TF_ASSIGN_OR_RETURN( new_init_operands[idx], CloneBackwardChain(*while_loop->parent(), loop_analysis.GetMoveInfos()[i], chain_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id)); if (postprocess_peeled.has_value()) { TF_RETURN_IF_ERROR(postprocess_peeled.value()(new_init_operands[idx])); } } ConstantValue next_loop_iteration = loop_analysis.GetLoopStart()->add(*loop_analysis.GetLoopIncrement()); const Shape& loop_index_shape = while_loop->shape().tuple_shapes(*loop_analysis.GetLoopIterationIdx()); HloInstruction* next_iteration_idx = while_loop->parent()->AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))); new_parameter_shapes.back() = loop_parameter->shape().tuple_shapes( *loop_analysis.GetLoopIterationIdx()); new_init_operands.back() = next_iteration_idx; auto body_builder = HloComputation::Builder(while_body->name()); HloInstruction* new_loop_param = body_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "param")); HloInstruction* loop_iterator_for_pipelined_instrs = body_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_loop_param, new_init_operands.size() - 1)); InstructionMap while_body_replacement_map; while_body_replacement_map[loop_parameter] = new_loop_param; InstructionMap collective_to_move_clone_map; collective_to_move_clone_map[loop_parameter] = new_loop_param; for (auto* u : loop_parameter->users()) { if (IsLoopIterator(u, *loop_analysis.GetLoopIterationIdx())) { collective_to_move_clone_map[u] = loop_iterator_for_pipelined_instrs; } } // Record the loop variant parameters used in the backward chain. LoopVariantParameterInfo loop_variant_parameter_info; // Clone loop in the body of the new loop. We change some things like // input/output shapes and how we connect loop iterator to the original // chains that we are pipelining. for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } HloInstruction* cloned_instr = nullptr; auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { TF_ASSIGN_OR_RETURN( cloned_instr, CloneBackwardChain(body_builder, loop_analysis.GetMoveInfos()[it->second], collective_to_move_clone_map, *loop_analysis.GetLoopIterationIdx(), next_channel_id, &loop_variant_parameter_info)); if (postprocess_rotated.has_value()) { TF_RETURN_IF_ERROR(postprocess_rotated.value()(cloned_instr)); } } else { auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); cloned_instr = body_builder.AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); } if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = body_builder.AddInstruction( HloInstruction::CreateGetTupleElement(new_loop_param, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; new_root_operands[tuple_idx] = cloned_instr; continue; } while_body_replacement_map[instr] = cloned_instr; } // For each loop variant parameter used in the backward chain, we temporarily // use a newly added loop parameter in the cloned loop. We now need to replace // this temporary value with an element in the loop output tuple. The index // of the element in the tuple is the same as the index of the loop variant // parameter before we pipeline the loop. for (const auto& [idx, value] : loop_variant_parameter_info) { auto it = while_body_replacement_map.find(new_root_operands[idx]); CHECK(it != while_body_replacement_map.end()) << new_root_operands[idx]->ToString() << " not present in map"; TF_RETURN_IF_ERROR(value->ReplaceAllUsesWith(it->second)); } new_root_operands.back() = body_builder.AddInstruction(HloInstruction::CreateBinary( loop_index_shape, HloOpcode::kAdd, while_body_replacement_map [new_root_operands[*loop_analysis.GetLoopIterationIdx()]], body_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_index_shape, next_loop_iteration.GetSignedValue()))))); HloInstruction* new_loop_root = body_builder.AddInstruction(HloInstruction::CreateTuple( MapNewOperands(new_root_operands, while_body_replacement_map, /*allow_unmapped=*/true))); while_body_replacement_map[while_body->root_instruction()] = new_loop_root; HloComputation* new_while_body = while_loop->GetModule()->AddEmbeddedComputation( body_builder.Build(new_loop_root)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_root, while_body_replacement_map)); for (HloInstruction* instruction : new_while_body->instructions()) { TF_RETURN_IF_ERROR(UpdateSendRecvValidation( instruction, false, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); } absl::flat_hash_map<const HloInstruction*, HloInstruction*> loop_cond_replacements; auto cond_builder = HloComputation::Builder(while_loop->while_condition()->name()); HloInstruction* new_cond_param = cond_builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeTupleShape(new_parameter_shapes), "cond_param")); // Update the loop bound of the loop to iterate one iteration less. // The updated bound is loop_start + (num_iterations-1) * loop_increment. HloInstruction* loop_bound = cond_builder.AddInstruction( HloInstruction::CreateConstant(*CreateLiteralOfShape( loop_initial_iteration_idx->shape(), loop_analysis.GetLoopStart() ->add(loop_analysis.GetLoopIterationCount() ->sub(ConstantValue::GetOne( loop_analysis.GetLoopStart()->GetBitwidth(), loop_analysis.GetLoopStart()->IsSigned())) .mul(*loop_analysis.GetLoopIncrement())) .GetSignedValue()))); // Construct the new loop condition computation. ComparisonDirection cd = loop_analysis.GetLoopIncrement()->GetSignedValue() > 0 ? ComparisonDirection::kLt : ComparisonDirection::kGt; HloInstruction* loop_iterator = cond_builder.AddInstruction(HloInstruction::CreateGetTupleElement( new_cond_param, *loop_analysis.GetLoopIterationIdx())); HloInstruction* comparison = cond_builder.AddInstruction(HloInstruction::CreateCompare( while_loop->while_condition()->root_instruction()->shape(), loop_iterator, loop_bound, cd)); HloComputation* new_while_condition = while_loop->GetModule()->AddEmbeddedComputation( cond_builder.Build(comparison)); HloInstruction* new_loop_init = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(new_init_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(while_body->root_instruction(), new_loop_init, chain_clone_map)); // Create the new loop. HloInstruction* new_while_loop = while_loop->parent()->AddInstruction(HloInstruction::CreateWhile( new_while_body->root_instruction()->shape(), new_while_condition, new_while_body, new_loop_init)); // Clone the loop body in the parent computation of the loop. This is the // peeled computation that happens after the loop happened to handle the // computation that we peeled away. while_body_replacement_map.clear(); while_body_replacement_map[loop_parameter] = new_while_loop; std::vector<HloInstruction*> output_tuple_instructions( while_loop->shape().tuple_shapes_size(), nullptr); for (auto* instr : while_body->MakeInstructionPostOrder()) { if (instr == loop_parameter || instr == while_body->root_instruction() || sideeffect_unused_instructions.contains(instr)) { continue; } auto instruction_is_output_it = is_output_instruction.find(instr); auto it = collective_to_move_map.find(instr); if (it != collective_to_move_map.end()) { const int64_t tuple_idx = while_loop->shape().tuple_shapes_size() + it->second; HloInstruction* pipelined_value = while_loop->parent()->AddInstruction( HloInstruction::CreateGetTupleElement(new_while_loop, tuple_idx)); while_body_replacement_map[instr] = pipelined_value; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = pipelined_value; } continue; } auto new_operands = MapNewOperands(instr->operands(), while_body_replacement_map); HloInstruction* cloned_instr = while_loop->parent()->AddInstruction( instr->CloneWithNewOperands(instr->shape(), new_operands)); TF_RETURN_IF_ERROR(UpdateControlDependencies(instr, cloned_instr, while_body_replacement_map)); UpdateInstructionChannelId(cloned_instr, next_channel_id); TF_RETURN_IF_ERROR(UpdateSendRecvValidation( cloned_instr, true, CollectivePipeliner::PipeliningDirection::kBackward, loop_analysis)); while_body_replacement_map[instr] = cloned_instr; if (instruction_is_output_it != is_output_instruction.end()) { output_tuple_instructions[instruction_is_output_it->second] = cloned_instr; } } // Substitute old loop with the result of the last peeled iteration. HloInstruction* final_loop_output = while_loop->parent()->AddInstruction( HloInstruction::CreateTuple(output_tuple_instructions)); HloComputation* loop_computation = while_loop->parent(); TF_RETURN_IF_ERROR( while_loop->ReplaceAllUsesWithDifferentShape(final_loop_output)); TF_RETURN_IF_ERROR( loop_computation->RemoveInstructionAndUnusedOperands(while_loop)); TF_RETURN_IF_ERROR(loop_computation->parent()->RemoveUnusedComputations()); return absl::OkStatus(); } absl::StatusOr<bool> CollectivePipeliner::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { CHECK(config_.acceptable_formatting); CHECK(config_.should_process); bool changed = false; std::vector<HloInstruction*> while_loop_instructions; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kWhile) { while_loop_instructions.push_back(instruction); } } } int64_t transformed_loops = 0; int64_t transformed_instructions = 0; int64_t next_channel_id = hlo_query::NextChannelId(*module); VLOG(1) << "Pipelining on direction: " << GetPipelineDirectionString(config_.pipelining_direction); for (HloInstruction* instruction : while_loop_instructions) { VLOG(1) << "While: " << instruction->ToString(); WhileLoopAnalysis loop_analysis( instruction, config_.max_pipelining_per_loop, config_.pipeline_use_tree, config_.process_different_sized_ops); loop_analysis.ComputeLoopStatistics(); if (!loop_analysis.GetLoopIterationCount() || loop_analysis.GetLoopIterationCount()->GetUnsignedValue() == 0) { continue; } VLOG(1) << "While iterations: " << loop_analysis.GetLoopIterationCount()->ToString(); loop_analysis.CollectCollectivesToMove( config_.level_to_operate_on, config_.pipelining_direction, config_.should_process, config_.acceptable_formatting, config_.should_allow_loop_variant_parameter_in_chain, config_.should_allow_control_dependencies, config_.should_add_loop_invariant_op_in_chain); if (loop_analysis.GetMoveInfos().empty()) { continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); VLOG(1) << "Found Collectives to optimize"; if (VLOG_IS_ON(1)) { for (auto& to_move : loop_analysis.GetMoveInfos()) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); if (to_move.dynamic_update_slice) { VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } VLOG(1) << "\t" << to_move.output_idx; } } if (config_.pipelining_direction == PipeliningDirection::kForward) { CHECK(config_.reuse_pipelined_op_buffer); TF_RETURN_IF_ERROR(TransformLoopForward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.reuse_pipelined_op_buffer, next_channel_id)); } else if (config_.pipelining_direction == PipeliningDirection::kForwardSink) { TF_RETURN_IF_ERROR(TransformLoopForwardSink( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.pipeline_use_tree, config_.process_different_sized_ops, config_.should_process, next_channel_id)); } else { CHECK_EQ(config_.pipelining_direction, PipeliningDirection::kBackward); TF_RETURN_IF_ERROR(TransformLoopBackward( loop_analysis, !config_.last_run, config_.level_to_operate_on, config_.process_different_sized_ops, config_.should_process, config_.acceptable_formatting, config_.postprocess_backward_peeled_op, config_.postprocess_backward_rotated_op, next_channel_id)); } ++transformed_loops; changed = true; } // If this is the last expected run then remove all the custom-calls that we // inserted as they shouldn't reach the backend. if (config_.last_run) { std::vector<HloInstruction*> to_remove; for (HloComputation* computation : module->MakeComputationPostOrder()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall( CollectivePipeliner::kInsertedByPreviousStep)) { to_remove.push_back(instruction); TF_RETURN_IF_ERROR( instruction->ReplaceAllUsesWith(instruction->mutable_operand(0))); changed = true; } } } for (auto* instruction : to_remove) { TF_RETURN_IF_ERROR( instruction->parent()->RemoveInstructionAndUnusedOperands( instruction)); } } VLOG(1) << "Transformed loops: " << transformed_loops << " and transformed instructions: " << transformed_instructions << " for pipelining direction: " << GetPipelineDirectionString(config_.pipelining_direction); // Run necessary cleanup to make sure unused code doesn't trigger HloVerifier. if (changed) { TF_RETURN_IF_ERROR(HloDCE().Run(module, execution_threads).status()); } int64_t transformed_instructions = 0; << GetPipelineDirectionString(config_.pipelining_direction); continue; } transformed_instructions += loop_analysis.GetMoveInfos().size(); if (VLOG_IS_ON(1)) { VLOG(1) << "\t" << to_move.collective_to_move->ToString(); VLOG(1) << "\t" << to_move.dynamic_update_slice->ToString(); } } } // namespace xla
#include "xla/service/collective_pipeliner.h" #include <memory> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/tests/filecheck.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class CollectivePipelinerTest : public HloTestBase { public: CollectivePipelinerTest() { const int64_t kNumReplicas = 4; const int64_t kNumComputations = 2; config_ = GetModuleConfigForTest(/*replica_count=*/kNumReplicas, /*num_partitions=*/kNumComputations); } protected: const HloPredicate IsAllGather = HloPredicateIsOp<HloOpcode::kAllGather>; HloModuleConfig config_; }; TEST_F(CollectivePipelinerTest, UpdateSendRecvChannelIdForHostTransfers) { constexpr absl::string_view hlo_string = R"( HloModule module add { lhs = bf16[] parameter(0) rhs = bf16[] parameter(1) ROOT add = bf16[] add(lhs, rhs) } while_cond { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) gte = s32[] get-tuple-element(param), index=0 constant.1 = s32[] constant(3) ROOT cmp = pred[] compare(gte, constant.1), direction=LT } while_body { param = (s32[], bf16[3,8,128], bf16[3,8,128]) parameter(0) get-tuple-element.394 = s32[] get-tuple-element(param), index=0 get-tuple-element.395 = bf16[3,8,128] get-tuple-element(param), index=1 get-tuple-element.5 = bf16[3,8,128] get-tuple-element(param), index=2 constant.2557 = s32[] constant(1) add.230 = s32[] add(get-tuple-element.394, constant.2557) constant.2559 = s32[] constant(3) subtract.139 = s32[] subtract(constant.2559, get-tuple-element.394) constant.2560 = s32[] constant(-1) add.231 = s32[] add(subtract.139, constant.2560) constant.2561 = s32[] constant(0) compare.747 = pred[] compare(add.231, constant.2561), direction=LT constant.2562 = s32[] constant(2) add.232 = s32[] add(subtract.139, constant.2562) after-all = after-all() send.88 = (s32[], u32[], token[]) send( add.232, after-all), channel_id=2, is_host_transfer=true send-done.88 = token[] send-done(send.88), channel_id=2, is_host_transfer=true select.1348 = s32[] select(compare.747, add.232, add.231) dynamic-slice.99 = bf16[1,8,128] dynamic-slice(get-tuple-element.5, select.1348, constant.2561, constant.2561), dynamic_slice_sizes={1,8,128} mul = bf16[1,8,128] multiply(dynamic-slice.99, dynamic-slice.99) ar.1 = bf16[1,8,128] all-reduce(mul), replica_groups={}, to_apply=add, channel_id=1 dynamic-update-slice.35 = bf16[3,8,128] dynamic-update-slice(get-tuple-element.395, ar.1, select.1348, constant.2561, constant.2561) ROOT tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(add.230, dynamic-update-slice.35, get-tuple-element.5) } ENTRY entry { c0 = s32[] constant(0) p0 = bf16[3,8,128] parameter(0) tuple = (s32[], bf16[3,8,128], bf16[3,8,128]) tuple(c0, p0, p0) while = (s32[], bf16[3,8,128], bf16[3,8,128]) while(tuple), condition=while_cond, body=while_body ROOT gte1 = bf16[3,8,128] get-tuple-element(while), index=1 } )"; auto module = ParseAndReturnUnverifiedModule(hlo_string, config_).value(); EXPECT_TRUE(RunOptimizer(module.get(), /*last_run=*/true).value()); XLA_VLOG_LINES(1, module->ToString()); auto* entry_comp = module->entry_computation(); auto* unrolled_send_done = entry_comp->GetInstructionWithName("send-done.0"); ASSERT_THAT(unrolled_send_done, ::testing::NotNull()); auto* unrolled_send = unrolled_send_done->operand(0); auto channel_id = [](const HloInstruction* instr) { return DynCast<HloChannelInstruction>(instr)->channel_id(); }; EXPECT_EQ(channel_id(unrolled_send), channel_id(unrolled_send_done)); }
ConvCanonicalizationTest_CanonicalStaysTheSame
xla/service/cpu/conv_canonicalization_test.cc
absl::StatusOr<bool> ConvCanonicalization::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloInstruction* hlo : module->entry_computation()->MakeInstructionPostOrder()) { if (hlo->opcode() == HloOpcode::kConvolution && !PotentiallyImplementedAsEigenConvolution(*hlo, target_machine_features_)) { const ConvolutionDimensionNumbers& dnums = hlo->convolution_dimension_numbers(); auto input_batch_dim = dnums.input_batch_dimension(); auto input_feature_dim = dnums.input_feature_dimension(); auto kernel_input_feature_dim = dnums.kernel_input_feature_dimension(); auto kernel_output_feature_dim = dnums.kernel_output_feature_dimension(); const int64_t num_spatial_dims = dnums.output_spatial_dimensions_size(); const int64_t num_dims = num_spatial_dims + 2; // A canonical convolution's dimension numbers need to satisfy the // following conditions (see cs/PotentiallyImplementedAsEigenConvolution). // // - the input is in NHWC order. // - the kernel is in HWIO order. // // For simplicity, as a first step, we reshape the input and filter to // NHWC and HWIO order, respectively. This may lose precision but won't // break the soundness. HloInstruction* input = hlo->mutable_operand(0); std::vector<int64_t> new_input_dim_order(num_dims); std::vector<int64_t> new_input_dims(num_dims); new_input_dim_order[0] = input_batch_dim; new_input_dims[0] = input->shape().dimensions(input_batch_dim); for (int64_t i = 0; i < num_spatial_dims; ++i) { new_input_dim_order[i + 1] = dnums.input_spatial_dimensions(i); new_input_dims[i + 1] = input->shape().dimensions(dnums.input_spatial_dimensions(i)); } new_input_dim_order[num_dims - 1] = input_feature_dim; new_input_dims[num_dims - 1] = input->shape().dimensions(input_feature_dim); Shape new_input_shape = ShapeUtil::MakeShape(input->shape().element_type(), new_input_dims); HloInstruction* new_input = module->entry_computation()->AddInstruction( HloInstruction::CreateTranspose(new_input_shape, input, new_input_dim_order)); HloInstruction* kernel = hlo->mutable_operand(1); std::vector<int64_t> new_kernel_dim_order(num_dims); std::vector<int64_t> new_kernel_dims(num_dims); for (int64_t i = 0; i < num_spatial_dims; ++i) { new_kernel_dim_order[i] = dnums.kernel_spatial_dimensions(i); new_kernel_dims[i] = kernel->shape().dimensions(dnums.kernel_spatial_dimensions(i)); } new_kernel_dim_order[num_dims - 2] = kernel_input_feature_dim; new_kernel_dims[num_dims - 2] = kernel->shape().dimensions(kernel_input_feature_dim); new_kernel_dim_order[num_dims - 1] = kernel_output_feature_dim; new_kernel_dims[num_dims - 1] = kernel->shape().dimensions(kernel_output_feature_dim); Shape new_kernel_shape = ShapeUtil::MakeShape(kernel->shape().element_type(), new_kernel_dims); HloInstruction* new_kernel = module->entry_computation()->AddInstruction( HloInstruction::CreateTranspose(new_kernel_shape, kernel, new_kernel_dim_order)); std::vector<int64_t> new_output_dim_order(num_dims); std::vector<int64_t> new_conv_dims(num_dims); auto output_batch_dim = dnums.output_batch_dimension(); auto output_feature_dim = dnums.output_feature_dimension(); new_output_dim_order[0] = output_batch_dim; new_conv_dims[0] = hlo->shape().dimensions(output_batch_dim); for (int64_t i = 0; i < num_spatial_dims; ++i) { new_output_dim_order[i + 1] = dnums.output_spatial_dimensions(i); new_conv_dims[i + 1] = hlo->shape().dimensions(dnums.output_spatial_dimensions(i)); } new_output_dim_order[num_dims - 1] = output_feature_dim; new_conv_dims[num_dims - 1] = hlo->shape().dimensions(output_feature_dim); Shape new_conv_shape = ShapeUtil::MakeShape(hlo->shape().element_type(), new_conv_dims); ConvolutionDimensionNumbers new_dnums; new_dnums.set_input_batch_dimension(0); new_dnums.set_output_batch_dimension(0); for (int64_t i = 0; i < num_spatial_dims; ++i) { new_dnums.add_input_spatial_dimensions(i + 1); new_dnums.add_kernel_spatial_dimensions(i); new_dnums.add_output_spatial_dimensions(i + 1); } new_dnums.set_input_feature_dimension(num_dims - 1); new_dnums.set_output_feature_dimension(num_dims - 1); new_dnums.set_kernel_input_feature_dimension(num_dims - 2); new_dnums.set_kernel_output_feature_dimension(num_dims - 1); // The window of the old convolution is reused, because reshapes only // change the dimension mapping but not the dimension sizes. For // example, input height and width are the same as before the reshapes. HloInstruction* new_conv = module->entry_computation()->AddInstruction( HloInstruction::CreateConvolve( new_conv_shape, new_input, new_kernel, hlo->feature_group_count(), hlo->batch_group_count(), hlo->window(), new_dnums, hlo->precision_config())); // Reshape the output back to the shape of the original convolution. TF_RETURN_IF_ERROR(module->entry_computation()->ReplaceWithNewInstruction( hlo, HloInstruction::CreateTranspose( hlo->shape(), new_conv, InversePermutation(new_output_dim_order)))); changed = true; } } return changed; }
#include "xla/service/cpu/conv_canonicalization.h" #include <vector> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/service/cpu/target_machine_features_fake.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class ConvCanonicalizationTest : public HloTestBase { public: ConvCanonicalizationTest() { for (int i = 0; i < 2; ++i) { auto dim = conv_window_.add_dimensions(); dim->set_size(kWindowSize); dim->set_stride(1); dim->set_padding_low(0); dim->set_padding_high(0); dim->set_window_dilation(1); dim->set_base_dilation(1); } } protected: Window conv_window_; static constexpr int kBatchSize = 50; static constexpr int kInputSize = 28; static constexpr int kWindowSize = 5; static constexpr int kInputFeatureCount = 32; static constexpr int kOutputFeatureCount = 64; }; TEST_F(ConvCanonicalizationTest, CanonicalStaysTheSame) { auto builder = HloComputation::Builder(TestName()); // The input dimensions are in NHWC order. auto input = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR4FromArray4D(Array4D<float>( kBatchSize, kInputSize, kInputSize, kInputFeatureCount)))); // The kernel dimensions are in HWIO order. auto kernel = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR4FromArray4D(Array4D<float>( kWindowSize, kWindowSize, kInputFeatureCount, kOutputFeatureCount)))); ConvolutionDimensionNumbers dnums; dnums.set_input_batch_dimension(0); dnums.set_output_batch_dimension(0); dnums.add_input_spatial_dimensions(1); dnums.add_output_spatial_dimensions(1); dnums.add_input_spatial_dimensions(2); dnums.add_output_spatial_dimensions(2); dnums.set_input_feature_dimension(3); dnums.set_output_feature_dimension(3); dnums.add_kernel_spatial_dimensions(0); dnums.add_kernel_spatial_dimensions(1); dnums.set_kernel_input_feature_dimension(2); dnums.set_kernel_output_feature_dimension(3); auto output_size = kInputSize - kWindowSize + 1; builder.AddInstruction(HloInstruction::CreateConvolve( ShapeUtil::MakeShape( F32, {kBatchSize, output_size, output_size, kOutputFeatureCount}), input, kernel, /*feature_group_count=*/1, /*batch_group_count=*/1, conv_window_, dnums, DefaultPrecisionConfig(2))); auto module = CreateNewVerifiedModule(); module->AddEntryComputation(builder.Build()); cpu::TargetMachineFeaturesWithFakeAlignmentLogic target_machine_features( [](int64_t shape_size) { return cpu::TargetMachineFeatures::kEigenExpectedTensorAlignment; }); ConvCanonicalization conv_canonicalization(&target_machine_features); EXPECT_FALSE(conv_canonicalization.Run(module.get()).value()); }
ConvCanonicalizationTest_NonCanonicalToCanonical
xla/service/cpu/conv_canonicalization_test.cc
absl::StatusOr<bool> ConvCanonicalization::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloInstruction* hlo : module->entry_computation()->MakeInstructionPostOrder()) { if (hlo->opcode() == HloOpcode::kConvolution && !PotentiallyImplementedAsEigenConvolution(*hlo, target_machine_features_)) { const ConvolutionDimensionNumbers& dnums = hlo->convolution_dimension_numbers(); auto input_batch_dim = dnums.input_batch_dimension(); auto input_feature_dim = dnums.input_feature_dimension(); auto kernel_input_feature_dim = dnums.kernel_input_feature_dimension(); auto kernel_output_feature_dim = dnums.kernel_output_feature_dimension(); const int64_t num_spatial_dims = dnums.output_spatial_dimensions_size(); const int64_t num_dims = num_spatial_dims + 2; // A canonical convolution's dimension numbers need to satisfy the // following conditions (see cs/PotentiallyImplementedAsEigenConvolution). // // - the input is in NHWC order. // - the kernel is in HWIO order. // // For simplicity, as a first step, we reshape the input and filter to // NHWC and HWIO order, respectively. This may lose precision but won't // break the soundness. HloInstruction* input = hlo->mutable_operand(0); std::vector<int64_t> new_input_dim_order(num_dims); std::vector<int64_t> new_input_dims(num_dims); new_input_dim_order[0] = input_batch_dim; new_input_dims[0] = input->shape().dimensions(input_batch_dim); for (int64_t i = 0; i < num_spatial_dims; ++i) { new_input_dim_order[i + 1] = dnums.input_spatial_dimensions(i); new_input_dims[i + 1] = input->shape().dimensions(dnums.input_spatial_dimensions(i)); } new_input_dim_order[num_dims - 1] = input_feature_dim; new_input_dims[num_dims - 1] = input->shape().dimensions(input_feature_dim); Shape new_input_shape = ShapeUtil::MakeShape(input->shape().element_type(), new_input_dims); HloInstruction* new_input = module->entry_computation()->AddInstruction( HloInstruction::CreateTranspose(new_input_shape, input, new_input_dim_order)); HloInstruction* kernel = hlo->mutable_operand(1); std::vector<int64_t> new_kernel_dim_order(num_dims); std::vector<int64_t> new_kernel_dims(num_dims); for (int64_t i = 0; i < num_spatial_dims; ++i) { new_kernel_dim_order[i] = dnums.kernel_spatial_dimensions(i); new_kernel_dims[i] = kernel->shape().dimensions(dnums.kernel_spatial_dimensions(i)); } new_kernel_dim_order[num_dims - 2] = kernel_input_feature_dim; new_kernel_dims[num_dims - 2] = kernel->shape().dimensions(kernel_input_feature_dim); new_kernel_dim_order[num_dims - 1] = kernel_output_feature_dim; new_kernel_dims[num_dims - 1] = kernel->shape().dimensions(kernel_output_feature_dim); Shape new_kernel_shape = ShapeUtil::MakeShape(kernel->shape().element_type(), new_kernel_dims); HloInstruction* new_kernel = module->entry_computation()->AddInstruction( HloInstruction::CreateTranspose(new_kernel_shape, kernel, new_kernel_dim_order)); std::vector<int64_t> new_output_dim_order(num_dims); std::vector<int64_t> new_conv_dims(num_dims); auto output_batch_dim = dnums.output_batch_dimension(); auto output_feature_dim = dnums.output_feature_dimension(); new_output_dim_order[0] = output_batch_dim; new_conv_dims[0] = hlo->shape().dimensions(output_batch_dim); for (int64_t i = 0; i < num_spatial_dims; ++i) { new_output_dim_order[i + 1] = dnums.output_spatial_dimensions(i); new_conv_dims[i + 1] = hlo->shape().dimensions(dnums.output_spatial_dimensions(i)); } new_output_dim_order[num_dims - 1] = output_feature_dim; new_conv_dims[num_dims - 1] = hlo->shape().dimensions(output_feature_dim); Shape new_conv_shape = ShapeUtil::MakeShape(hlo->shape().element_type(), new_conv_dims); ConvolutionDimensionNumbers new_dnums; new_dnums.set_input_batch_dimension(0); new_dnums.set_output_batch_dimension(0); for (int64_t i = 0; i < num_spatial_dims; ++i) { new_dnums.add_input_spatial_dimensions(i + 1); new_dnums.add_kernel_spatial_dimensions(i); new_dnums.add_output_spatial_dimensions(i + 1); } new_dnums.set_input_feature_dimension(num_dims - 1); new_dnums.set_output_feature_dimension(num_dims - 1); new_dnums.set_kernel_input_feature_dimension(num_dims - 2); new_dnums.set_kernel_output_feature_dimension(num_dims - 1); // The window of the old convolution is reused, because reshapes only // change the dimension mapping but not the dimension sizes. For // example, input height and width are the same as before the reshapes. HloInstruction* new_conv = module->entry_computation()->AddInstruction( HloInstruction::CreateConvolve( new_conv_shape, new_input, new_kernel, hlo->feature_group_count(), hlo->batch_group_count(), hlo->window(), new_dnums, hlo->precision_config())); // Reshape the output back to the shape of the original convolution. TF_RETURN_IF_ERROR(module->entry_computation()->ReplaceWithNewInstruction( hlo, HloInstruction::CreateTranspose( hlo->shape(), new_conv, InversePermutation(new_output_dim_order)))); changed = true; } } return changed; }
#include "xla/service/cpu/conv_canonicalization.h" #include <vector> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/service/cpu/target_machine_features_fake.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" class ConvCanonicalizationTest : public HloTestBase { public: ConvCanonicalizationTest() { for (int i = 0; i < 2; ++i) { auto dim = conv_window_.add_dimensions(); dim->set_size(kWindowSize); dim->set_stride(1); dim->set_padding_low(0); dim->set_padding_high(0); dim->set_window_dilation(1); dim->set_base_dilation(1); } } protected: Window conv_window_; static constexpr int kBatchSize = 50; static constexpr int kInputSize = 28; static constexpr int kWindowSize = 5; static constexpr int kInputFeatureCount = 32; static constexpr int kOutputFeatureCount = 64; }; TEST_F(ConvCanonicalizationTest, NonCanonicalToCanonical) { auto builder = HloComputation::Builder(TestName()); // The input dimensions are in CNHW order. auto input = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR4FromArray4D(Array4D<float>( kInputFeatureCount, kBatchSize, kInputSize, kInputSize)))); // The kernel dimensions are in OIHW order. auto kernel = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR4FromArray4D(Array4D<float>( kOutputFeatureCount, kInputFeatureCount, kWindowSize, kWindowSize)))); ConvolutionDimensionNumbers dnums; dnums.set_input_batch_dimension(1); dnums.set_output_batch_dimension(1); dnums.add_input_spatial_dimensions(2); dnums.add_output_spatial_dimensions(2); dnums.add_input_spatial_dimensions(3); dnums.add_output_spatial_dimensions(3); dnums.set_input_feature_dimension(0); dnums.set_output_feature_dimension(0); dnums.add_kernel_spatial_dimensions(2); dnums.add_kernel_spatial_dimensions(3); dnums.set_kernel_input_feature_dimension(1); dnums.set_kernel_output_feature_dimension(0); auto output_size = kInputSize - kWindowSize + 1; builder.AddInstruction(HloInstruction::CreateConvolve( ShapeUtil::MakeShape( F32, {kOutputFeatureCount, kBatchSize, output_size, output_size}), input, kernel, /*feature_group_count=*/1, /*batch_group_count=*/1, conv_window_, dnums, DefaultPrecisionConfig(2))); auto module = CreateNewVerifiedModule(); HloComputation* entry_computation = module->AddEntryComputation(builder.Build()); cpu::TargetMachineFeaturesWithFakeAlignmentLogic target_machine_features( [](int64_t shape_size) { return cpu::TargetMachineFeatures::kEigenExpectedTensorAlignment; }); ConvCanonicalization conv_canonicalization(&target_machine_features); EXPECT_TRUE(conv_canonicalization.Run(module.get()).value()); const HloInstruction* output_reshape = entry_computation->root_instruction(); EXPECT_EQ(HloOpcode::kTranspose, output_reshape->opcode()); const HloInstruction* canonical_conv = output_reshape->operand(0); EXPECT_EQ(HloOpcode::kConvolution, canonical_conv->opcode()); const HloInstruction* input_reshape = canonical_conv->operand(0); EXPECT_EQ(HloOpcode::kTranspose, input_reshape->opcode()); const HloInstruction* kernel_reshape = canonical_conv->operand(1); EXPECT_EQ(HloOpcode::kTranspose, kernel_reshape->opcode()); // The input is in CNHW order. input_reshape should produce // NHWC for the convolution to hit the Eigen fast path. EXPECT_THAT(input_reshape->dimensions(), ElementsAre(1, 2, 3, 0)); // The kernel is in OIHW order. kernel_reshape should produce // HWIO for the convolution to hit the Eigen fast path. EXPECT_THAT(kernel_reshape->dimensions(), ElementsAre(2, 3, 1, 0)); // The output of the canonical convolution is in NHWC order (the same as // input_reshape's order). output_reshape should restore that order to the // order of the computation root (CNHW). EXPECT_THAT(output_reshape->dimensions(), ElementsAre(3, 0, 1, 2)); }
CpuLayoutAssignmentTest_BatchDotLayoutMustBeRowMajor
xla/service/cpu/cpu_layout_assignment_test.cc
static bool ShouldMakeAllUsersColMajor(const HloInstruction* instruction) { for (auto* user : instruction->users()) { optional<int64_t> operand_idx = ProfitableToMakeDotOperandColumnMajor(*user); if (!operand_idx || user->operand(*operand_idx) != instruction || absl::c_count(user->operands(), instruction) != 1) { return false; } } return true; } static optional<int64_t> ShouldMakeOperandColumnMajor( ShouldMakeOperandColMajorCache* cache, const HloInstruction& instruction) { optional<int64_t> operand_idx = ProfitableToMakeDotOperandColumnMajor(instruction); if (!operand_idx) { return nullopt; } const HloInstruction* operand = instruction.operand(*operand_idx); if (operand->opcode() != HloOpcode::kConstant) { return nullopt; } auto it = cache->find(operand); if (it == cache->end()) { auto insert_result = cache->insert({operand, ShouldMakeAllUsersColMajor(operand)}); CHECK(insert_result.second); it = insert_result.first; } return it->second ? operand_idx : nullopt; } &shape, [](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } std::vector<int64_t> dimension_order(subshape->dimensions_size()); std::iota(dimension_order.rbegin(), dimension_order.rend(), 0); *subshape->mutable_layout() = LayoutUtil::MakeLayout(dimension_order); }); static Shape ColMajorShape(const Shape& old_shape) { Shape new_shape(old_shape); std::vector<int64_t> dimension_order(new_shape.dimensions_size()); std::iota(dimension_order.begin(), dimension_order.end(), 0); *new_shape.mutable_layout() = LayoutUtil::MakeLayout(dimension_order); return new_shape; } static bool OperandsAndResultMustHaveRowMajorLayout( const HloInstruction& instr, const TargetMachineFeatures& target_machine_features) { if (instr.opcode() == HloOpcode::kConvolution) { return PotentiallyImplementedAsEigenConvolution(instr, target_machine_features); } else if (instr.opcode() == HloOpcode::kDot) { return DotOperandsAndResultMustHaveRowMajorLayout(instr, target_machine_features); } else if (instr.opcode() == HloOpcode::kCustomCall) { return instr.custom_call_target() == "TopK"; } return false; } absl::Status CpuLayoutAssignment::AddBackendConstraints( LayoutConstraints* constraints) { ShouldMakeOperandColMajorCache cache; const HloComputation* computation = constraints->computation(); for (auto* instruction : computation->instructions()) { if (OperandsAndResultMustHaveRowMajorLayout(*instruction, target_machine_features_)) { TF_RETURN_IF_ERROR(SetInstructionLayout( RowMajorShape(instruction->shape()), instruction)); for (int i = 0; i < instruction->operand_count(); i++) { TF_RETURN_IF_ERROR(SetOperandLayout( RowMajorShape(instruction->operand(i)->shape()), instruction, i)); } } else if (optional<int64_t> op_idx = ShouldMakeOperandColumnMajor(&cache, *instruction)) { const HloInstruction* op = instruction->operand(*op_idx); TF_RETURN_IF_ERROR( SetOperandLayout(ColMajorShape(op->shape()), instruction, *op_idx)); } else if (instruction->opcode() == HloOpcode::kReduceScatter) { // XLA:CPU can only support reduce-scatter where the scatter dimension // is the most major dimension in the layout. auto ars = Cast<HloReduceScatterInstruction>(instruction); TF_RETURN_IF_ERROR(SetInstructionLayout( ShapeUtil::MoveDimToMajor(ars->shape(), ars->scatter_dimension()), ars)); } else if (instruction->opcode() == HloOpcode::kAllGather) { // XLA:CPU can only support all-gathers where the gather dimension is the // most major dimension in the layout. auto ag = Cast<HloAllGatherInstruction>(instruction); TF_RETURN_IF_ERROR(SetInstructionLayout( ShapeUtil::MoveDimToMajor(ag->shape(), ag->all_gather_dimension()), ag)); } else { for (int64_t operand_no = 0; operand_no < instruction->operand_count(); ++operand_no) { // Skip operands which already have a constraint. if (constraints->OperandLayout(instruction, operand_no) != nullptr) { continue; } // Skip over forwarded operands. if (AnyOperandBufferForwarded(instruction, operand_no)) { continue; } // Skip operands with non-array shapes. if (!instruction->operand(operand_no)->shape().IsArray()) { continue; } Shape operand_shape( RowMajorShape(instruction->operand(operand_no)->shape())); TF_RETURN_IF_ERROR( SetOperandLayout(operand_shape, instruction, operand_no)); } // Skip over the root instruction for the top-level computation. if (computation->parent()->entry_computation() == computation && computation->root_instruction() == instruction) { continue; } // Skip instructions which don't produce array shapes (tuples, opaque, // etc.). if (!instruction->shape().IsArray()) { continue; } } } return absl::OkStatus(); }
#include "xla/service/cpu/cpu_layout_assignment.h" #include <initializer_list> #include <memory> #include <utility> #include <vector> #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/hlo/utils/hlo_matchers.h" #include "xla/layout_util.h" #include "xla/literal.h" #include "xla/service/algebraic_simplifier.h" #include "xla/service/computation_layout.h" #include "xla/service/cpu/target_machine_features_fake.h" #include "xla/shape_layout.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "xla/tests/test_utils.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/status.h" class CpuLayoutAssignmentTest : public HloTestBase { protected: void AssignLayouts(HloModule* module, ComputationLayout* entry_computation_layout) { cpu::TargetMachineFeaturesWithFakeAlignmentLogic target_machine_features( [](int64_t shape_size) { return cpu::TargetMachineFeatures::kEigenExpectedTensorAlignment; }); cpu::CpuLayoutAssignment layout_assignment(entry_computation_layout, &target_machine_features); EXPECT_IS_OK(layout_assignment.Run(module).status()); } }; TEST_F(CpuLayoutAssignmentTest, BatchDotLayoutMustBeRowMajor) { const char* hlo_string = R"( HloModule BatchDotLayoutMustBeRowMajor ENTRY BatchDotLayoutMustBeRowMajor { p0 = f32[10,1,10] parameter(0) p1 = f32[10,10,1] parameter(1) ROOT dot = f32[10,1,1] dot(p0, p1), lhs_batch_dims={0}, lhs_contracting_dims={2}, rhs_batch_dims={0}, rhs_contracting_dims={1} } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); HloComputation* computation = module->entry_computation(); ComputationLayout computation_layout(computation->ComputeProgramShape()); *computation_layout.mutable_parameter_layout(0) = ShapeLayout( ShapeUtil::MakeShapeWithDenseLayout(F32, {10, 1, 10}, {2, 1, 0})); *computation_layout.mutable_parameter_layout(1) = ShapeLayout( ShapeUtil::MakeShapeWithDenseLayout(F32, {10, 10, 1}, {2, 1, 0})); *computation_layout.mutable_result_layout() = ShapeLayout( ShapeUtil::MakeShapeWithDenseLayout(F32, {10, 1, 1}, {1, 2, 0})); AssignLayouts(module.get(), &computation_layout); Shape expected_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {10, 1, 1}, {2, 1, 0}); EXPECT_THAT(module->entry_computation()->root_instruction(), op::Copy(op::ShapeWithLayout(expected_shape))); EXPECT_THAT( module->entry_computation()->root_instruction(), op::Copy(op::Dot( op::ShapeWithLayout(computation_layout.parameter_layout(0).shape()), op::ShapeWithLayout( computation_layout.parameter_layout(1).shape())))); }
CpuLayoutAssignmentTest_DotWithConstantLhsTensor
xla/service/cpu/cpu_layout_assignment_test.cc
static bool ShouldMakeAllUsersColMajor(const HloInstruction* instruction) { for (auto* user : instruction->users()) { optional<int64_t> operand_idx = ProfitableToMakeDotOperandColumnMajor(*user); if (!operand_idx || user->operand(*operand_idx) != instruction || absl::c_count(user->operands(), instruction) != 1) { return false; } } return true; } static optional<int64_t> ShouldMakeOperandColumnMajor( ShouldMakeOperandColMajorCache* cache, const HloInstruction& instruction) { optional<int64_t> operand_idx = ProfitableToMakeDotOperandColumnMajor(instruction); if (!operand_idx) { return nullopt; } const HloInstruction* operand = instruction.operand(*operand_idx); if (operand->opcode() != HloOpcode::kConstant) { return nullopt; } auto it = cache->find(operand); if (it == cache->end()) { auto insert_result = cache->insert({operand, ShouldMakeAllUsersColMajor(operand)}); CHECK(insert_result.second); it = insert_result.first; } return it->second ? operand_idx : nullopt; } &shape, [](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } std::vector<int64_t> dimension_order(subshape->dimensions_size()); std::iota(dimension_order.rbegin(), dimension_order.rend(), 0); *subshape->mutable_layout() = LayoutUtil::MakeLayout(dimension_order); }); static Shape ColMajorShape(const Shape& old_shape) { Shape new_shape(old_shape); std::vector<int64_t> dimension_order(new_shape.dimensions_size()); std::iota(dimension_order.begin(), dimension_order.end(), 0); *new_shape.mutable_layout() = LayoutUtil::MakeLayout(dimension_order); return new_shape; } static bool OperandsAndResultMustHaveRowMajorLayout( const HloInstruction& instr, const TargetMachineFeatures& target_machine_features) { if (instr.opcode() == HloOpcode::kConvolution) { return PotentiallyImplementedAsEigenConvolution(instr, target_machine_features); } else if (instr.opcode() == HloOpcode::kDot) { return DotOperandsAndResultMustHaveRowMajorLayout(instr, target_machine_features); } else if (instr.opcode() == HloOpcode::kCustomCall) { return instr.custom_call_target() == "TopK"; } return false; } absl::Status CpuLayoutAssignment::AddBackendConstraints( LayoutConstraints* constraints) { ShouldMakeOperandColMajorCache cache; const HloComputation* computation = constraints->computation(); for (auto* instruction : computation->instructions()) { if (OperandsAndResultMustHaveRowMajorLayout(*instruction, target_machine_features_)) { TF_RETURN_IF_ERROR(SetInstructionLayout( RowMajorShape(instruction->shape()), instruction)); for (int i = 0; i < instruction->operand_count(); i++) { TF_RETURN_IF_ERROR(SetOperandLayout( RowMajorShape(instruction->operand(i)->shape()), instruction, i)); } } else if (optional<int64_t> op_idx = ShouldMakeOperandColumnMajor(&cache, *instruction)) { const HloInstruction* op = instruction->operand(*op_idx); TF_RETURN_IF_ERROR( SetOperandLayout(ColMajorShape(op->shape()), instruction, *op_idx)); } else if (instruction->opcode() == HloOpcode::kReduceScatter) { // XLA:CPU can only support reduce-scatter where the scatter dimension // is the most major dimension in the layout. auto ars = Cast<HloReduceScatterInstruction>(instruction); TF_RETURN_IF_ERROR(SetInstructionLayout( ShapeUtil::MoveDimToMajor(ars->shape(), ars->scatter_dimension()), ars)); } else if (instruction->opcode() == HloOpcode::kAllGather) { // XLA:CPU can only support all-gathers where the gather dimension is the // most major dimension in the layout. auto ag = Cast<HloAllGatherInstruction>(instruction); TF_RETURN_IF_ERROR(SetInstructionLayout( ShapeUtil::MoveDimToMajor(ag->shape(), ag->all_gather_dimension()), ag)); } else { for (int64_t operand_no = 0; operand_no < instruction->operand_count(); ++operand_no) { // Skip operands which already have a constraint. if (constraints->OperandLayout(instruction, operand_no) != nullptr) { continue; } // Skip over forwarded operands. if (AnyOperandBufferForwarded(instruction, operand_no)) { continue; } // Skip operands with non-array shapes. if (!instruction->operand(operand_no)->shape().IsArray()) { continue; } Shape operand_shape( RowMajorShape(instruction->operand(operand_no)->shape())); TF_RETURN_IF_ERROR( SetOperandLayout(operand_shape, instruction, operand_no)); } // Skip over the root instruction for the top-level computation. if (computation->parent()->entry_computation() == computation && computation->root_instruction() == instruction) { continue; } // Skip instructions which don't produce array shapes (tuples, opaque, // etc.). if (!instruction->shape().IsArray()) { continue; } } } return absl::OkStatus(); }
#include "xla/service/cpu/cpu_layout_assignment.h" #include <initializer_list> #include <memory> #include <utility> #include <vector> #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/hlo/utils/hlo_matchers.h" #include "xla/layout_util.h" #include "xla/literal.h" #include "xla/service/algebraic_simplifier.h" #include "xla/service/computation_layout.h" #include "xla/service/cpu/target_machine_features_fake.h" #include "xla/shape_layout.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "xla/tests/test_utils.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/status.h" class CpuLayoutAssignmentTest : public HloTestBase { protected: void AssignLayouts(HloModule* module, ComputationLayout* entry_computation_layout) { cpu::TargetMachineFeaturesWithFakeAlignmentLogic target_machine_features( [](int64_t shape_size) { return cpu::TargetMachineFeatures::kEigenExpectedTensorAlignment; }); cpu::CpuLayoutAssignment layout_assignment(entry_computation_layout, &target_machine_features); EXPECT_IS_OK(layout_assignment.Run(module).status()); } }; TEST_F(CpuLayoutAssignmentTest, DotWithConstantLhsTensor) { auto builder = HloComputation::Builder(TestName()); Shape lhs_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {1, 12}, {0, 1}); Shape rhs_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {12, 24}, {0, 1}); Shape result_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {1, 24}, {0, 1}); auto dot_lhs = builder.AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(lhs_shape))); auto dot_rhs = builder.AddInstruction( HloInstruction::CreateParameter(0, rhs_shape, "param0")); auto dot_result = builder.AddInstruction( CreateCanonicalDot(result_shape, dot_lhs, dot_rhs)); auto module = CreateNewVerifiedModule(); HloComputation* computation = module->AddEntryComputation(builder.Build()); ComputationLayout computation_layout(computation->ComputeProgramShape()); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(LayoutUtil::GetWithDefaultLayout(rhs_shape)); *computation_layout.mutable_result_layout() = ShapeLayout(LayoutUtil::GetWithDefaultLayout(result_shape)); AssignLayouts(module.get(), &computation_layout); for (HloInstruction* instruction : {dot_lhs, dot_rhs, dot_result}) { EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeLayout({1, 0}), instruction->shape().layout())); } for (const auto& instruction : computation->instructions()) { EXPECT_NE(instruction->opcode(), HloOpcode::kCopy); } }
CpuLayoutAssignmentTest_DotWithConstantRhsTensor
xla/service/cpu/cpu_layout_assignment_test.cc
static bool ShouldMakeAllUsersColMajor(const HloInstruction* instruction) { for (auto* user : instruction->users()) { optional<int64_t> operand_idx = ProfitableToMakeDotOperandColumnMajor(*user); if (!operand_idx || user->operand(*operand_idx) != instruction || absl::c_count(user->operands(), instruction) != 1) { return false; } } return true; } static optional<int64_t> ShouldMakeOperandColumnMajor( ShouldMakeOperandColMajorCache* cache, const HloInstruction& instruction) { optional<int64_t> operand_idx = ProfitableToMakeDotOperandColumnMajor(instruction); if (!operand_idx) { return nullopt; } const HloInstruction* operand = instruction.operand(*operand_idx); if (operand->opcode() != HloOpcode::kConstant) { return nullopt; } auto it = cache->find(operand); if (it == cache->end()) { auto insert_result = cache->insert({operand, ShouldMakeAllUsersColMajor(operand)}); CHECK(insert_result.second); it = insert_result.first; } return it->second ? operand_idx : nullopt; } &shape, [](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } std::vector<int64_t> dimension_order(subshape->dimensions_size()); std::iota(dimension_order.rbegin(), dimension_order.rend(), 0); *subshape->mutable_layout() = LayoutUtil::MakeLayout(dimension_order); }); static Shape ColMajorShape(const Shape& old_shape) { Shape new_shape(old_shape); std::vector<int64_t> dimension_order(new_shape.dimensions_size()); std::iota(dimension_order.begin(), dimension_order.end(), 0); *new_shape.mutable_layout() = LayoutUtil::MakeLayout(dimension_order); return new_shape; } static bool OperandsAndResultMustHaveRowMajorLayout( const HloInstruction& instr, const TargetMachineFeatures& target_machine_features) { if (instr.opcode() == HloOpcode::kConvolution) { return PotentiallyImplementedAsEigenConvolution(instr, target_machine_features); } else if (instr.opcode() == HloOpcode::kDot) { return DotOperandsAndResultMustHaveRowMajorLayout(instr, target_machine_features); } else if (instr.opcode() == HloOpcode::kCustomCall) { return instr.custom_call_target() == "TopK"; } return false; } absl::Status CpuLayoutAssignment::AddBackendConstraints( LayoutConstraints* constraints) { ShouldMakeOperandColMajorCache cache; const HloComputation* computation = constraints->computation(); for (auto* instruction : computation->instructions()) { if (OperandsAndResultMustHaveRowMajorLayout(*instruction, target_machine_features_)) { TF_RETURN_IF_ERROR(SetInstructionLayout( RowMajorShape(instruction->shape()), instruction)); for (int i = 0; i < instruction->operand_count(); i++) { TF_RETURN_IF_ERROR(SetOperandLayout( RowMajorShape(instruction->operand(i)->shape()), instruction, i)); } } else if (optional<int64_t> op_idx = ShouldMakeOperandColumnMajor(&cache, *instruction)) { const HloInstruction* op = instruction->operand(*op_idx); TF_RETURN_IF_ERROR( SetOperandLayout(ColMajorShape(op->shape()), instruction, *op_idx)); } else if (instruction->opcode() == HloOpcode::kReduceScatter) { // XLA:CPU can only support reduce-scatter where the scatter dimension // is the most major dimension in the layout. auto ars = Cast<HloReduceScatterInstruction>(instruction); TF_RETURN_IF_ERROR(SetInstructionLayout( ShapeUtil::MoveDimToMajor(ars->shape(), ars->scatter_dimension()), ars)); } else if (instruction->opcode() == HloOpcode::kAllGather) { // XLA:CPU can only support all-gathers where the gather dimension is the // most major dimension in the layout. auto ag = Cast<HloAllGatherInstruction>(instruction); TF_RETURN_IF_ERROR(SetInstructionLayout( ShapeUtil::MoveDimToMajor(ag->shape(), ag->all_gather_dimension()), ag)); } else { for (int64_t operand_no = 0; operand_no < instruction->operand_count(); ++operand_no) { // Skip operands which already have a constraint. if (constraints->OperandLayout(instruction, operand_no) != nullptr) { continue; } // Skip over forwarded operands. if (AnyOperandBufferForwarded(instruction, operand_no)) { continue; } // Skip operands with non-array shapes. if (!instruction->operand(operand_no)->shape().IsArray()) { continue; } Shape operand_shape( RowMajorShape(instruction->operand(operand_no)->shape())); TF_RETURN_IF_ERROR( SetOperandLayout(operand_shape, instruction, operand_no)); } // Skip over the root instruction for the top-level computation. if (computation->parent()->entry_computation() == computation && computation->root_instruction() == instruction) { continue; } // Skip instructions which don't produce array shapes (tuples, opaque, // etc.). if (!instruction->shape().IsArray()) { continue; } } } return absl::OkStatus(); }
#include "xla/service/cpu/cpu_layout_assignment.h" #include <initializer_list> #include <memory> #include <utility> #include <vector> #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/hlo/utils/hlo_matchers.h" #include "xla/layout_util.h" #include "xla/literal.h" #include "xla/service/algebraic_simplifier.h" #include "xla/service/computation_layout.h" #include "xla/service/cpu/target_machine_features_fake.h" #include "xla/shape_layout.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "xla/tests/test_utils.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/status.h" class CpuLayoutAssignmentTest : public HloTestBase { protected: void AssignLayouts(HloModule* module, ComputationLayout* entry_computation_layout) { cpu::TargetMachineFeaturesWithFakeAlignmentLogic target_machine_features( [](int64_t shape_size) { return cpu::TargetMachineFeatures::kEigenExpectedTensorAlignment; }); cpu::CpuLayoutAssignment layout_assignment(entry_computation_layout, &target_machine_features); EXPECT_IS_OK(layout_assignment.Run(module).status()); } }; TEST_F(CpuLayoutAssignmentTest, DotWithConstantRhsTensor) { auto builder = HloComputation::Builder(TestName()); Shape lhs_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {12}, {0}); Shape rhs_shape = ShapeUtil::MakeShape(F32, {12, 24}); Shape result_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {24}, {0}); auto dot_lhs = builder.AddInstruction( HloInstruction::CreateParameter(0, lhs_shape, "param0")); auto dot_rhs = builder.AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(rhs_shape))); auto result = builder.AddInstruction( CreateCanonicalDot(result_shape, dot_lhs, dot_rhs)); auto module = CreateNewVerifiedModule(); HloComputation* computation = module->AddEntryComputation(builder.Build()); ComputationLayout computation_layout(computation->ComputeProgramShape()); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(LayoutUtil::GetWithDefaultLayout(lhs_shape)); *computation_layout.mutable_result_layout() = ShapeLayout(LayoutUtil::GetWithDefaultLayout(result_shape)); AssignLayouts(module.get(), &computation_layout); EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeLayout({0}), dot_lhs->shape().layout())); EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeLayout({0, 1}), dot_rhs->shape().layout())); EXPECT_TRUE( LayoutUtil::Equal(LayoutUtil::MakeLayout({0}), result->shape().layout())); for (const auto& instruction : computation->instructions()) { EXPECT_NE(instruction->opcode(), HloOpcode::kCopy); } }
CpuLayoutAssignmentTest_DotWithConstantRhsTensorThroughGTE
xla/service/cpu/cpu_layout_assignment_test.cc
static bool ShouldMakeAllUsersColMajor(const HloInstruction* instruction) { for (auto* user : instruction->users()) { optional<int64_t> operand_idx = ProfitableToMakeDotOperandColumnMajor(*user); if (!operand_idx || user->operand(*operand_idx) != instruction || absl::c_count(user->operands(), instruction) != 1) { return false; } } return true; } static optional<int64_t> ShouldMakeOperandColumnMajor( ShouldMakeOperandColMajorCache* cache, const HloInstruction& instruction) { optional<int64_t> operand_idx = ProfitableToMakeDotOperandColumnMajor(instruction); if (!operand_idx) { return nullopt; } const HloInstruction* operand = instruction.operand(*operand_idx); if (operand->opcode() != HloOpcode::kConstant) { return nullopt; } auto it = cache->find(operand); if (it == cache->end()) { auto insert_result = cache->insert({operand, ShouldMakeAllUsersColMajor(operand)}); CHECK(insert_result.second); it = insert_result.first; } return it->second ? operand_idx : nullopt; } &shape, [](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } std::vector<int64_t> dimension_order(subshape->dimensions_size()); std::iota(dimension_order.rbegin(), dimension_order.rend(), 0); *subshape->mutable_layout() = LayoutUtil::MakeLayout(dimension_order); }); static Shape ColMajorShape(const Shape& old_shape) { Shape new_shape(old_shape); std::vector<int64_t> dimension_order(new_shape.dimensions_size()); std::iota(dimension_order.begin(), dimension_order.end(), 0); *new_shape.mutable_layout() = LayoutUtil::MakeLayout(dimension_order); return new_shape; } static bool OperandsAndResultMustHaveRowMajorLayout( const HloInstruction& instr, const TargetMachineFeatures& target_machine_features) { if (instr.opcode() == HloOpcode::kConvolution) { return PotentiallyImplementedAsEigenConvolution(instr, target_machine_features); } else if (instr.opcode() == HloOpcode::kDot) { return DotOperandsAndResultMustHaveRowMajorLayout(instr, target_machine_features); } else if (instr.opcode() == HloOpcode::kCustomCall) { return instr.custom_call_target() == "TopK"; } return false; } absl::Status CpuLayoutAssignment::AddBackendConstraints( LayoutConstraints* constraints) { ShouldMakeOperandColMajorCache cache; const HloComputation* computation = constraints->computation(); for (auto* instruction : computation->instructions()) { if (OperandsAndResultMustHaveRowMajorLayout(*instruction, target_machine_features_)) { TF_RETURN_IF_ERROR(SetInstructionLayout( RowMajorShape(instruction->shape()), instruction)); for (int i = 0; i < instruction->operand_count(); i++) { TF_RETURN_IF_ERROR(SetOperandLayout( RowMajorShape(instruction->operand(i)->shape()), instruction, i)); } } else if (optional<int64_t> op_idx = ShouldMakeOperandColumnMajor(&cache, *instruction)) { const HloInstruction* op = instruction->operand(*op_idx); TF_RETURN_IF_ERROR( SetOperandLayout(ColMajorShape(op->shape()), instruction, *op_idx)); } else if (instruction->opcode() == HloOpcode::kReduceScatter) { // XLA:CPU can only support reduce-scatter where the scatter dimension // is the most major dimension in the layout. auto ars = Cast<HloReduceScatterInstruction>(instruction); TF_RETURN_IF_ERROR(SetInstructionLayout( ShapeUtil::MoveDimToMajor(ars->shape(), ars->scatter_dimension()), ars)); } else if (instruction->opcode() == HloOpcode::kAllGather) { // XLA:CPU can only support all-gathers where the gather dimension is the // most major dimension in the layout. auto ag = Cast<HloAllGatherInstruction>(instruction); TF_RETURN_IF_ERROR(SetInstructionLayout( ShapeUtil::MoveDimToMajor(ag->shape(), ag->all_gather_dimension()), ag)); } else { for (int64_t operand_no = 0; operand_no < instruction->operand_count(); ++operand_no) { // Skip operands which already have a constraint. if (constraints->OperandLayout(instruction, operand_no) != nullptr) { continue; } // Skip over forwarded operands. if (AnyOperandBufferForwarded(instruction, operand_no)) { continue; } // Skip operands with non-array shapes. if (!instruction->operand(operand_no)->shape().IsArray()) { continue; } Shape operand_shape( RowMajorShape(instruction->operand(operand_no)->shape())); TF_RETURN_IF_ERROR( SetOperandLayout(operand_shape, instruction, operand_no)); } // Skip over the root instruction for the top-level computation. if (computation->parent()->entry_computation() == computation && computation->root_instruction() == instruction) { continue; } // Skip instructions which don't produce array shapes (tuples, opaque, // etc.). if (!instruction->shape().IsArray()) { continue; } } } return absl::OkStatus(); }
#include "xla/service/cpu/cpu_layout_assignment.h" #include <initializer_list> #include <memory> #include <utility> #include <vector> #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/hlo/utils/hlo_matchers.h" #include "xla/layout_util.h" #include "xla/literal.h" #include "xla/service/algebraic_simplifier.h" #include "xla/service/computation_layout.h" #include "xla/service/cpu/target_machine_features_fake.h" #include "xla/shape_layout.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "xla/tests/test_utils.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/status.h" class CpuLayoutAssignmentTest : public HloTestBase { protected: void AssignLayouts(HloModule* module, ComputationLayout* entry_computation_layout) { cpu::TargetMachineFeaturesWithFakeAlignmentLogic target_machine_features( [](int64_t shape_size) { return cpu::TargetMachineFeatures::kEigenExpectedTensorAlignment; }); cpu::CpuLayoutAssignment layout_assignment(entry_computation_layout, &target_machine_features); EXPECT_IS_OK(layout_assignment.Run(module).status()); } }; TEST_F(CpuLayoutAssignmentTest, DotWithConstantRhsTensorThroughGTE) { // This is a case we could theoretically optimize at some point, but today we // don't. auto builder = HloComputation::Builder(TestName()); Shape lhs_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {1, 12}, {0, 1}); Shape rhs_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {12, 24}, {0, 1}); Shape other_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {100, 24}, {0, 1}); auto constant_shape = ShapeUtil::MakeTupleShape({other_shape, rhs_shape}); auto constant = builder.AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(constant_shape))); Shape result_shape = ShapeUtil::MakeShape(F32, {1, 24}); auto dot_lhs = builder.AddInstruction( HloInstruction::CreateParameter(0, lhs_shape, "param0")); auto dot_rhs = builder.AddInstruction( HloInstruction::CreateGetTupleElement(rhs_shape, constant, 1)); auto dot_result = builder.AddInstruction( CreateCanonicalDot(result_shape, dot_lhs, dot_rhs)); auto module = CreateNewVerifiedModule(); HloComputation* computation = module->AddEntryComputation(builder.Build()); ComputationLayout computation_layout(computation->ComputeProgramShape()); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(LayoutUtil::GetWithDefaultLayout(lhs_shape)); *computation_layout.mutable_result_layout() = ShapeLayout(LayoutUtil::GetWithDefaultLayout(result_shape)); AssignLayouts(module.get(), &computation_layout); for (HloInstruction* instruction : {dot_lhs, dot_rhs, dot_result}) { EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeLayout({1, 0}), instruction->shape().layout())); } for (const auto& instruction : computation->instructions()) { EXPECT_NE(instruction->opcode(), HloOpcode::kCopy); } }
CpuLayoutAssignmentTest_MultipleDotsWithSameConstantRhsTensor0
xla/service/cpu/cpu_layout_assignment_test.cc
static bool ShouldMakeAllUsersColMajor(const HloInstruction* instruction) { for (auto* user : instruction->users()) { optional<int64_t> operand_idx = ProfitableToMakeDotOperandColumnMajor(*user); if (!operand_idx || user->operand(*operand_idx) != instruction || absl::c_count(user->operands(), instruction) != 1) { return false; } } return true; } static optional<int64_t> ShouldMakeOperandColumnMajor( ShouldMakeOperandColMajorCache* cache, const HloInstruction& instruction) { optional<int64_t> operand_idx = ProfitableToMakeDotOperandColumnMajor(instruction); if (!operand_idx) { return nullopt; } const HloInstruction* operand = instruction.operand(*operand_idx); if (operand->opcode() != HloOpcode::kConstant) { return nullopt; } auto it = cache->find(operand); if (it == cache->end()) { auto insert_result = cache->insert({operand, ShouldMakeAllUsersColMajor(operand)}); CHECK(insert_result.second); it = insert_result.first; } return it->second ? operand_idx : nullopt; } &shape, [](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } std::vector<int64_t> dimension_order(subshape->dimensions_size()); std::iota(dimension_order.rbegin(), dimension_order.rend(), 0); *subshape->mutable_layout() = LayoutUtil::MakeLayout(dimension_order); }); static Shape ColMajorShape(const Shape& old_shape) { Shape new_shape(old_shape); std::vector<int64_t> dimension_order(new_shape.dimensions_size()); std::iota(dimension_order.begin(), dimension_order.end(), 0); *new_shape.mutable_layout() = LayoutUtil::MakeLayout(dimension_order); return new_shape; } static bool OperandsAndResultMustHaveRowMajorLayout( const HloInstruction& instr, const TargetMachineFeatures& target_machine_features) { if (instr.opcode() == HloOpcode::kConvolution) { return PotentiallyImplementedAsEigenConvolution(instr, target_machine_features); } else if (instr.opcode() == HloOpcode::kDot) { return DotOperandsAndResultMustHaveRowMajorLayout(instr, target_machine_features); } else if (instr.opcode() == HloOpcode::kCustomCall) { return instr.custom_call_target() == "TopK"; } return false; } absl::Status CpuLayoutAssignment::AddBackendConstraints( LayoutConstraints* constraints) { ShouldMakeOperandColMajorCache cache; const HloComputation* computation = constraints->computation(); for (auto* instruction : computation->instructions()) { if (OperandsAndResultMustHaveRowMajorLayout(*instruction, target_machine_features_)) { TF_RETURN_IF_ERROR(SetInstructionLayout( RowMajorShape(instruction->shape()), instruction)); for (int i = 0; i < instruction->operand_count(); i++) { TF_RETURN_IF_ERROR(SetOperandLayout( RowMajorShape(instruction->operand(i)->shape()), instruction, i)); } } else if (optional<int64_t> op_idx = ShouldMakeOperandColumnMajor(&cache, *instruction)) { const HloInstruction* op = instruction->operand(*op_idx); TF_RETURN_IF_ERROR( SetOperandLayout(ColMajorShape(op->shape()), instruction, *op_idx)); } else if (instruction->opcode() == HloOpcode::kReduceScatter) { // XLA:CPU can only support reduce-scatter where the scatter dimension // is the most major dimension in the layout. auto ars = Cast<HloReduceScatterInstruction>(instruction); TF_RETURN_IF_ERROR(SetInstructionLayout( ShapeUtil::MoveDimToMajor(ars->shape(), ars->scatter_dimension()), ars)); } else if (instruction->opcode() == HloOpcode::kAllGather) { // XLA:CPU can only support all-gathers where the gather dimension is the // most major dimension in the layout. auto ag = Cast<HloAllGatherInstruction>(instruction); TF_RETURN_IF_ERROR(SetInstructionLayout( ShapeUtil::MoveDimToMajor(ag->shape(), ag->all_gather_dimension()), ag)); } else { for (int64_t operand_no = 0; operand_no < instruction->operand_count(); ++operand_no) { // Skip operands which already have a constraint. if (constraints->OperandLayout(instruction, operand_no) != nullptr) { continue; } // Skip over forwarded operands. if (AnyOperandBufferForwarded(instruction, operand_no)) { continue; } // Skip operands with non-array shapes. if (!instruction->operand(operand_no)->shape().IsArray()) { continue; } Shape operand_shape( RowMajorShape(instruction->operand(operand_no)->shape())); TF_RETURN_IF_ERROR( SetOperandLayout(operand_shape, instruction, operand_no)); } // Skip over the root instruction for the top-level computation. if (computation->parent()->entry_computation() == computation && computation->root_instruction() == instruction) { continue; } // Skip instructions which don't produce array shapes (tuples, opaque, // etc.). if (!instruction->shape().IsArray()) { continue; } } } return absl::OkStatus(); }
#include "xla/service/cpu/cpu_layout_assignment.h" #include <initializer_list> #include <memory> #include <utility> #include <vector> #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/hlo/utils/hlo_matchers.h" #include "xla/layout_util.h" #include "xla/literal.h" #include "xla/service/algebraic_simplifier.h" #include "xla/service/computation_layout.h" #include "xla/service/cpu/target_machine_features_fake.h" #include "xla/shape_layout.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "xla/tests/test_utils.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/status.h" class CpuLayoutAssignmentTest : public HloTestBase { protected: void AssignLayouts(HloModule* module, ComputationLayout* entry_computation_layout) { cpu::TargetMachineFeaturesWithFakeAlignmentLogic target_machine_features( [](int64_t shape_size) { return cpu::TargetMachineFeatures::kEigenExpectedTensorAlignment; }); cpu::CpuLayoutAssignment layout_assignment(entry_computation_layout, &target_machine_features); EXPECT_IS_OK(layout_assignment.Run(module).status()); } }; TEST_F(CpuLayoutAssignmentTest, MultipleDotsWithSameConstantRhsTensor0) { // Two dot products have the same constant as the RHS, and both those dot // products can be optimized if the constant has a column-major layout. auto builder = HloComputation::Builder(TestName()); Shape lhs_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {12}, {0}); Shape rhs_shape = ShapeUtil::MakeShape(F32, {12, 24}); Shape result_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {24}, {0}); auto dot_a_lhs = builder.AddInstruction( HloInstruction::CreateParameter(0, lhs_shape, "param0")); auto dot_b_lhs = builder.AddInstruction( HloInstruction::CreateParameter(1, lhs_shape, "param1")); auto dot_rhs = builder.AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(rhs_shape))); auto dot_a_result = builder.AddInstruction( CreateCanonicalDot(result_shape, dot_a_lhs, dot_rhs)); auto dot_b_result = builder.AddInstruction( CreateCanonicalDot(result_shape, dot_b_lhs, dot_rhs)); builder.AddInstruction(HloInstruction::CreateBinary( result_shape, HloOpcode::kAdd, dot_a_result, dot_b_result)); auto module = CreateNewVerifiedModule(); HloComputation* computation = module->AddEntryComputation(builder.Build()); ComputationLayout computation_layout(computation->ComputeProgramShape()); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(LayoutUtil::GetWithDefaultLayout(lhs_shape)); *computation_layout.mutable_result_layout() = ShapeLayout(LayoutUtil::GetWithDefaultLayout(result_shape)); AssignLayouts(module.get(), &computation_layout); EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeLayout({0, 1}), dot_rhs->shape().layout())); for (HloInstruction* instruction : {dot_a_lhs, dot_b_lhs, dot_a_result, dot_b_result}) { EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeLayout({0}), instruction->shape().layout())); } for (const auto& instruction : computation->instructions()) { EXPECT_NE(instruction->opcode(), HloOpcode::kCopy); } }
CpuLayoutAssignmentTest_MultipleDotsWithSameConstantRhsTensor1
xla/service/cpu/cpu_layout_assignment_test.cc
static bool ShouldMakeAllUsersColMajor(const HloInstruction* instruction) { for (auto* user : instruction->users()) { optional<int64_t> operand_idx = ProfitableToMakeDotOperandColumnMajor(*user); if (!operand_idx || user->operand(*operand_idx) != instruction || absl::c_count(user->operands(), instruction) != 1) { return false; } } return true; } static optional<int64_t> ShouldMakeOperandColumnMajor( ShouldMakeOperandColMajorCache* cache, const HloInstruction& instruction) { optional<int64_t> operand_idx = ProfitableToMakeDotOperandColumnMajor(instruction); if (!operand_idx) { return nullopt; } const HloInstruction* operand = instruction.operand(*operand_idx); if (operand->opcode() != HloOpcode::kConstant) { return nullopt; } auto it = cache->find(operand); if (it == cache->end()) { auto insert_result = cache->insert({operand, ShouldMakeAllUsersColMajor(operand)}); CHECK(insert_result.second); it = insert_result.first; } return it->second ? operand_idx : nullopt; } &shape, [](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } std::vector<int64_t> dimension_order(subshape->dimensions_size()); std::iota(dimension_order.rbegin(), dimension_order.rend(), 0); *subshape->mutable_layout() = LayoutUtil::MakeLayout(dimension_order); }); static Shape ColMajorShape(const Shape& old_shape) { Shape new_shape(old_shape); std::vector<int64_t> dimension_order(new_shape.dimensions_size()); std::iota(dimension_order.begin(), dimension_order.end(), 0); *new_shape.mutable_layout() = LayoutUtil::MakeLayout(dimension_order); return new_shape; } static bool OperandsAndResultMustHaveRowMajorLayout( const HloInstruction& instr, const TargetMachineFeatures& target_machine_features) { if (instr.opcode() == HloOpcode::kConvolution) { return PotentiallyImplementedAsEigenConvolution(instr, target_machine_features); } else if (instr.opcode() == HloOpcode::kDot) { return DotOperandsAndResultMustHaveRowMajorLayout(instr, target_machine_features); } else if (instr.opcode() == HloOpcode::kCustomCall) { return instr.custom_call_target() == "TopK"; } return false; } absl::Status CpuLayoutAssignment::AddBackendConstraints( LayoutConstraints* constraints) { ShouldMakeOperandColMajorCache cache; const HloComputation* computation = constraints->computation(); for (auto* instruction : computation->instructions()) { if (OperandsAndResultMustHaveRowMajorLayout(*instruction, target_machine_features_)) { TF_RETURN_IF_ERROR(SetInstructionLayout( RowMajorShape(instruction->shape()), instruction)); for (int i = 0; i < instruction->operand_count(); i++) { TF_RETURN_IF_ERROR(SetOperandLayout( RowMajorShape(instruction->operand(i)->shape()), instruction, i)); } } else if (optional<int64_t> op_idx = ShouldMakeOperandColumnMajor(&cache, *instruction)) { const HloInstruction* op = instruction->operand(*op_idx); TF_RETURN_IF_ERROR( SetOperandLayout(ColMajorShape(op->shape()), instruction, *op_idx)); } else if (instruction->opcode() == HloOpcode::kReduceScatter) { // XLA:CPU can only support reduce-scatter where the scatter dimension // is the most major dimension in the layout. auto ars = Cast<HloReduceScatterInstruction>(instruction); TF_RETURN_IF_ERROR(SetInstructionLayout( ShapeUtil::MoveDimToMajor(ars->shape(), ars->scatter_dimension()), ars)); } else if (instruction->opcode() == HloOpcode::kAllGather) { // XLA:CPU can only support all-gathers where the gather dimension is the // most major dimension in the layout. auto ag = Cast<HloAllGatherInstruction>(instruction); TF_RETURN_IF_ERROR(SetInstructionLayout( ShapeUtil::MoveDimToMajor(ag->shape(), ag->all_gather_dimension()), ag)); } else { for (int64_t operand_no = 0; operand_no < instruction->operand_count(); ++operand_no) { // Skip operands which already have a constraint. if (constraints->OperandLayout(instruction, operand_no) != nullptr) { continue; } // Skip over forwarded operands. if (AnyOperandBufferForwarded(instruction, operand_no)) { continue; } // Skip operands with non-array shapes. if (!instruction->operand(operand_no)->shape().IsArray()) { continue; } Shape operand_shape( RowMajorShape(instruction->operand(operand_no)->shape())); TF_RETURN_IF_ERROR( SetOperandLayout(operand_shape, instruction, operand_no)); } // Skip over the root instruction for the top-level computation. if (computation->parent()->entry_computation() == computation && computation->root_instruction() == instruction) { continue; } // Skip instructions which don't produce array shapes (tuples, opaque, // etc.). if (!instruction->shape().IsArray()) { continue; } } } return absl::OkStatus(); }
#include "xla/service/cpu/cpu_layout_assignment.h" #include <initializer_list> #include <memory> #include <utility> #include <vector> #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/hlo/utils/hlo_matchers.h" #include "xla/layout_util.h" #include "xla/literal.h" #include "xla/service/algebraic_simplifier.h" #include "xla/service/computation_layout.h" #include "xla/service/cpu/target_machine_features_fake.h" #include "xla/shape_layout.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "xla/tests/test_utils.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/status.h" class CpuLayoutAssignmentTest : public HloTestBase { protected: void AssignLayouts(HloModule* module, ComputationLayout* entry_computation_layout) { cpu::TargetMachineFeaturesWithFakeAlignmentLogic target_machine_features( [](int64_t shape_size) { return cpu::TargetMachineFeatures::kEigenExpectedTensorAlignment; }); cpu::CpuLayoutAssignment layout_assignment(entry_computation_layout, &target_machine_features); EXPECT_IS_OK(layout_assignment.Run(module).status()); } }; TEST_F(CpuLayoutAssignmentTest, MultipleDotsWithSameConstantRhsTensor1) { // Two dot products have the same constant as the RHS, but only one of the two // dot products can be optimized if the constant has a column-major layout. auto builder = HloComputation::Builder(TestName()); Shape lhs_a_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {1, 12}, {0, 1}); Shape lhs_b_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {2, 12}, {0, 1}); Shape rhs_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {12, 24}, {0, 1}); Shape result_a_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {1, 24}, {0, 1}); Shape result_b_shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {2, 24}, {0, 1}); auto dot_a_lhs = builder.AddInstruction( HloInstruction::CreateParameter(0, lhs_a_shape, "param0")); auto dot_b_lhs = builder.AddInstruction( HloInstruction::CreateParameter(1, lhs_b_shape, "param1")); auto dot_rhs = builder.AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(rhs_shape))); auto dot_a_result = builder.AddInstruction( CreateCanonicalDot(result_a_shape, dot_a_lhs, dot_rhs)); auto dot_b_result = builder.AddInstruction( CreateCanonicalDot(result_b_shape, dot_b_lhs, dot_rhs)); auto tuple_result = builder.AddInstruction( HloInstruction::CreateTuple({dot_a_result, dot_b_result})); auto module = CreateNewVerifiedModule(); HloComputation* computation = module->AddEntryComputation(builder.Build()); ComputationLayout computation_layout(computation->ComputeProgramShape()); *computation_layout.mutable_parameter_layout(0) = ShapeLayout(LayoutUtil::GetWithDefaultLayout(lhs_a_shape)); *computation_layout.mutable_parameter_layout(1) = ShapeLayout(LayoutUtil::GetWithDefaultLayout(lhs_b_shape)); *computation_layout.mutable_result_layout() = ShapeLayout(LayoutUtil::GetWithDefaultLayout(tuple_result->shape())); AssignLayouts(module.get(), &computation_layout); for (HloInstruction* instruction : {dot_rhs, dot_a_lhs, dot_b_lhs, dot_a_result, dot_b_result}) { EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeLayout({1, 0}), instruction->shape().layout())); } for (const auto& instruction : computation->instructions()) { EXPECT_NE(instruction->opcode(), HloOpcode::kCopy); } }
CpuRuntimeTest_FailureStatus
xla/service/cpu/cpu_runtime_test.cc
XfeedManager* GetXfeedManager(int device_ordinal) { static auto* managers = new absl::flat_hash_map<int, XfeedManager*>(); static absl::Mutex* mutex = new absl::Mutex(); absl::MutexLock lock(mutex); auto it = managers->find(device_ordinal); if (it == managers->end()) { it = managers->emplace(device_ordinal, new XfeedManager()).first; } return it->second; } absl::StatusOr<Shape> DecodeSelfDescribingShapeConstant(const void* shape_ptr, int32_t size_bytes) { ShapeProto shape_proto; if (!shape_proto.ParseFromArray(shape_ptr, size_bytes)) { return tsl::errors::Internal("Failed parsing the shape proto"); } Shape shape(shape_proto); auto status = ShapeUtil::ValidateShape(shape); if (!status.ok()) { return status; } return std::move(shape); } std::string ShapeString(const void* shape_ptr, int32_t shape_length) { absl::StatusOr<Shape> shape = DecodeSelfDescribingShapeConstant(shape_ptr, shape_length); if (shape.ok()) { return ShapeUtil::HumanStringWithLayout(shape.value()); } return "<invalid shape>"; } int GetDeviceOrdinal(const ExecutableRunOptions* run_options) { if (!run_options) { return 0; } else if (run_options->device_ordinal() != -1) { return run_options->device_ordinal(); } return run_options->stream()->parent()->device_ordinal(); } void* AcquireInfeedBufferForDequeueImpl(const ExecutableRunOptions* run_options, int32_t buffer_length, const void* shape, int32_t shape_length) { int device_ordinal = GetDeviceOrdinal(run_options); VLOG(2) << "AcquireInfeedBufferForDequeue: " << ShapeString(shape, shape_length) << " on stream executor " << device_ordinal; XfeedManager* xfeed = GetXfeedManager(device_ordinal); // Wait until there's a buffer to dequeue. XfeedBuffer* buffer = xfeed->infeed()->BlockingDequeueBuffer(); CHECK_EQ(buffer->length(), buffer_length) << "XLA program infeed request buffer size " << buffer_length << " did not match the runtime's infed buffer length " << buffer->length() << "; program reports desired shape: " << ShapeString(shape, shape_length); return buffer->data(); } VLOG(2) << "AcquireInfeedBufferForDequeue: " void ReleaseInfeedBufferAfterDequeueImpl( const ExecutableRunOptions* run_options, int32_t buffer_length, void* buffer_ptr, const void* shape_ptr, int32_t shape_length) { int device_ordinal = GetDeviceOrdinal(run_options); VLOG(2) << "ReleaseInfeedBufferAfterDeque: " << ShapeString(shape_ptr, shape_length) << " on stream executor " << device_ordinal; XfeedManager* xfeed = GetXfeedManager(device_ordinal); absl::StatusOr<Shape> shape = DecodeSelfDescribingShapeConstant(shape_ptr, shape_length); xfeed->infeed()->ReleaseCurrentBuffer(buffer_length, buffer_ptr, std::move(shape)); } VLOG(2) << "ReleaseInfeedBufferAfterDeque: " void* AcquireOutfeedBufferForPopulationImpl( const ExecutableRunOptions* run_options, int32_t buffer_length, const void* shape_ptr, int32_t shape_length) { int device_ordinal = GetDeviceOrdinal(run_options); VLOG(2) << "AcquireOutfeedBufferForPopulation: " << ShapeString(shape_ptr, shape_length) << " on stream executor " << device_ordinal; XfeedManager* xfeed = GetXfeedManager(device_ordinal); // Wait until there's a buffer to dequeue. XfeedBuffer* buffer = xfeed->outfeed()->BlockingDequeueBuffer(); CHECK_EQ(buffer->length(), buffer_length) << "XLA program outfeed request buffer size " << buffer_length << " did not match the runtime's outfeed buffer length " << buffer->length() << "; program reports outfed shape: " << ShapeString(shape_ptr, shape_length); return buffer->data(); } VLOG(2) << "AcquireOutfeedBufferForPopulation: " void ReleaseOutfeedBufferAfterPopulationImpl( const ExecutableRunOptions* run_options, int32_t buffer_length, void* buffer_ptr, const void* shape_ptr, int32_t shape_length) { int device_ordinal = GetDeviceOrdinal(run_options); VLOG(2) << "ReleaseOutfeedBufferAfterPopulation: " << ShapeString(shape_ptr, shape_length) << " on stream executor " << device_ordinal; XfeedManager* xfeed = GetXfeedManager(device_ordinal); absl::StatusOr<Shape> shape = DecodeSelfDescribingShapeConstant(shape_ptr, shape_length); xfeed->outfeed()->ReleaseCurrentBuffer(buffer_length, buffer_ptr, std::move(shape)); } VLOG(2) << "ReleaseOutfeedBufferAfterPopulation: " void ReplicaIdImpl(const ExecutableRunOptions* run_options, void* output_buffer) { int device_ordinal = GetDeviceOrdinal(run_options); int32_t replica_id = run_options->device_assignment() ->ReplicaIdForDevice(GlobalDeviceId(device_ordinal)) .value(); std::memcpy(output_buffer, &replica_id, 4); } void PartitionIdImpl(const ExecutableRunOptions* run_options, void* output_buffer) { int device_ordinal = GetDeviceOrdinal(run_options); const DeviceAssignment::LogicalID logical_id = run_options->device_assignment() ->LogicalIdForDevice(GlobalDeviceId(device_ordinal)) .value(); std::memcpy(output_buffer, &logical_id.computation_id, 4); } RendezvousKey GetRendezvousKey(const ExecutableRunOptions* run_options, GlobalDeviceId device, std::vector<ReplicaGroup> group, int32_t channel_id_present, std::optional<bool> use_global_device_ids, int64_t op_id) { const DeviceAssignment& device_assignment = *run_options->device_assignment(); RendezvousKey::CollectiveOpKind op_kind = channel_id_present ? RendezvousKey::kCrossModule : RendezvousKey::kCrossReplica; std::vector<GlobalDeviceId> participating_devices = GetParticipatingDevices(GlobalDeviceId(device), device_assignment, group, GetCollectiveOpGroupMode(channel_id_present != 0, use_global_device_ids) .value()) .value(); int num_local_participants = participating_devices.size(); return RendezvousKey{run_options->run_id(), std::move(participating_devices), num_local_participants, op_kind, op_id}; } CollectivesInterface* GetInProcessCollectivesImpl() { static InProcessCollectives* c = new InProcessCollectives(); return c; } CollectivesInterface* GetCollectivesImpl( const ExecutableRunOptions* run_options) { if (run_options->cpu_executable_run_options() && run_options->cpu_executable_run_options()->collectives()) { return run_options->cpu_executable_run_options()->collectives(); } return GetInProcessCollectivesImpl(); } absl::StatusOr<int> RankInGlobalDevices( absl::Span<GlobalDeviceId const> devices, GlobalDeviceId device) { auto it = absl::c_find(devices, device); if (it == devices.end()) { return InvalidArgument( "Device %d not present in global devices %s.", device.value(), absl::StrJoin(devices, ", ", [](std::string* out, GlobalDeviceId id) { absl::StrAppend(out, id.value()); })); } return std::distance(devices.begin(), it); } absl::StrJoin(devices, ", ", [](std::string* out, GlobalDeviceId id) { absl::StrAppend(out, id.value()); })); void AllToAllImpl(const ExecutableRunOptions* run_options, int32_t channel_id_present, int64_t op_id, const void* replica_groups_str, int32_t replica_groups_str_size, int32_t num_buffers, int64_t buffer_size, void** source_buffers, void** destination_buffers) { GlobalDeviceId device(GetDeviceOrdinal(run_options)); std::string_view replica_groups_serialized( static_cast<const char*>(replica_groups_str), replica_groups_str_size); std::vector<ReplicaGroup> group = ParseReplicaGroupsOnly(replica_groups_serialized).value(); RendezvousKey rendezvous_key = GetRendezvousKey(run_options, device, group, channel_id_present, /*use_global_device_ids=*/std::nullopt, op_id); int rank = RankInGlobalDevices(rendezvous_key.global_devices, device).value(); CollectivesInterface* collectives = GetCollectivesImpl(run_options); ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(source_buffers, sizeof(void*) * num_buffers); ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(destination_buffers, sizeof(void*) * num_buffers); auto communicator = collectives->GetCommunicator(rendezvous_key.global_devices, rank).value(); TF_CHECK_OK(communicator->AllToAll( rendezvous_key, buffer_size, absl::Span<const void* const>(source_buffers, num_buffers), absl::Span<void* const>(destination_buffers, num_buffers), DefaultCollectiveTimeout())); } void AllGatherImpl(const ExecutableRunOptions* run_options, int32_t channel_id_present, int32_t use_global_device_ids, int64_t op_id, const void* replica_groups_str, int32_t replica_groups_str_size, int64_t buffer_size, void* source_buffer, void* destination_buffer) { GlobalDeviceId device(GetDeviceOrdinal(run_options)); std::string_view replica_groups_serialized( static_cast<const char*>(replica_groups_str), replica_groups_str_size); std::vector<ReplicaGroup> group = ParseReplicaGroupsOnly(replica_groups_serialized).value(); RendezvousKey rendezvous_key = GetRendezvousKey(run_options, device, group, channel_id_present, use_global_device_ids, op_id); int rank = RankInGlobalDevices(rendezvous_key.global_devices, device).value(); CollectivesInterface* collectives = GetCollectivesImpl(run_options); auto communicator = collectives->GetCommunicator(rendezvous_key.global_devices, rank).value(); TF_CHECK_OK(communicator->AllGather(rendezvous_key, buffer_size, source_buffer, destination_buffer, DefaultCollectiveTimeout())); } void ReduceScatterImpl(const ExecutableRunOptions* run_options, const void* replica_groups_str, int32_t replica_groups_str_size, int32_t channel_id_present, int32_t use_global_device_ids, int64_t op_id, int32_t reduction_kind, int32_t element_type, int64_t chunk_elems, void* input_buffer, void* output_buffer) { GlobalDeviceId device(GetDeviceOrdinal(run_options)); std::string_view replica_groups_serialized( static_cast<const char*>(replica_groups_str), replica_groups_str_size); std::vector<ReplicaGroup> group = ParseReplicaGroupsOnly(replica_groups_serialized).value(); RendezvousKey rendezvous_key = GetRendezvousKey(run_options, device, group, channel_id_present, use_global_device_ids, op_id); int rank = RankInGlobalDevices(rendezvous_key.global_devices, device).value(); CollectivesInterface* collectives = GetCollectivesImpl(run_options); auto communicator = collectives->GetCommunicator(rendezvous_key.global_devices, rank).value(); TF_CHECK_OK(communicator->ReduceScatter( rendezvous_key, static_cast<ReductionKind>(reduction_kind), static_cast<PrimitiveType>(element_type), chunk_elems, input_buffer, output_buffer, DefaultCollectiveTimeout())); } void AllReduceImpl(const ExecutableRunOptions* run_options, const void* replica_groups_str, int32_t replica_groups_str_size, int32_t channel_id_present, int32_t use_global_device_ids, int64_t op_id, int32_t reduction_kind, const void* shape_ptr, int32_t shape_length, int32_t num_buffers, void** input_buffers, void** output_buffers) { GlobalDeviceId device(GetDeviceOrdinal(run_options)); std::string_view replica_groups_serialized( static_cast<const char*>(replica_groups_str), replica_groups_str_size); std::vector<ReplicaGroup> group = ParseReplicaGroupsOnly(replica_groups_serialized).value(); RendezvousKey rendezvous_key = GetRendezvousKey(run_options, device, group, channel_id_present, use_global_device_ids, op_id); auto shape_str = ShapeString(shape_ptr, shape_length); VLOG(2) << "All-reduce input/output shape : " << shape_str; Shape shape = DecodeSelfDescribingShapeConstant(shape_ptr, shape_length).value(); CHECK((num_buffers > 1 && shape.IsTuple()) || (num_buffers == 1 && LayoutUtil::IsDenseArray(shape))); int rank = RankInGlobalDevices(rendezvous_key.global_devices, device).value(); CollectivesInterface* collectives = GetCollectivesImpl(run_options); auto communicator = collectives->GetCommunicator(rendezvous_key.global_devices, rank).value(); for (int i = 0; i < num_buffers; i++) { Shape subshape = num_buffers == 1 ? shape : shape.tuple_shapes(i); TF_CHECK_OK(communicator->AllReduce( rendezvous_key, static_cast<ReductionKind>(reduction_kind), subshape.element_type(), ShapeUtil::ElementsIn(subshape), input_buffers[i], output_buffers[i], DefaultCollectiveTimeout())); } } VLOG(2) << "All-reduce input/output shape : " << shape_str; void CollectivePermuteImpl(const ExecutableRunOptions* run_options, int32_t channel_id_present, int64_t op_id, int32_t byte_size, void* input_buffer, void* output_buffer, const void* source_target_pairs, int32_t source_target_pairs_size) { GlobalDeviceId device(GetDeviceOrdinal(run_options)); std::string_view source_target_pairs_serialized( static_cast<const char*>(source_target_pairs), source_target_pairs_size); auto pairs = absl::StrSplit(source_target_pairs_serialized, ','); const DeviceAssignment::LogicalID logical_id = run_options->device_assignment()->LogicalIdForDevice(device).value(); int32_t logical_device_id = channel_id_present ? logical_id.computation_id : logical_id.replica_id; std::optional<int> source_replica_id; std::vector<int> copy_to; for (auto& p : pairs) { std::vector<std::string> mapping = absl::StrSplit(p, '='); CHECK_EQ(mapping.size(), 2); int from = std::stoi(mapping[0]); int to = std::stoi(mapping[1]); if (from == logical_device_id) { copy_to.push_back(to); } if (to == logical_device_id) { CHECK(!source_replica_id.has_value()); source_replica_id = from; } } RendezvousKey rendezvous_key = GetRendezvousKey(run_options, device, {}, channel_id_present, /*use_global_device_ids=*/std::nullopt, op_id); int rank = RankInGlobalDevices(rendezvous_key.global_devices, device).value(); CollectivesInterface* collectives = GetCollectivesImpl(run_options); auto communicator = collectives->GetCommunicator(rendezvous_key.global_devices, rank).value(); TF_CHECK_OK(communicator->CollectivePermute( rendezvous_key, byte_size, source_replica_id, copy_to, input_buffer, output_buffer, DefaultCollectiveTimeout())); } ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY int __xla_cpu_runtime_PrintfToStderr( const char* format, ...) { VLOG(3) << "__xla_cpu_runtime_PrintfToStderr " << format; va_list args; va_start(args, format); int result = vfprintf(stderr, format, args); va_end(args); return result; } VLOG(3) << "__xla_cpu_runtime_PrintfToStderr " << format; ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY int64_t __xla_cpu_runtime_TracingStart( const void* /* ExecutableRunOptions* run_options_ptr*/, const char* name, const char* hlo_module, int64_t program_id) { VLOG(3) << "TracingStart " << name; auto trace_in = tsl::profiler::TraceMeEncode(name, {{"hlo_op", name}, {"hlo_module", hlo_module}, {"program_id", program_id}}); return tsl::profiler::TraceMe::ActivityStart(trace_in); } VLOG(3) << "TracingStart " << name; ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_TracingEnd( const void* /* ExecutableRunOptions* run_options_ptr*/, int64_t id) { VLOG(3) << "TracingEnd " << id; tsl::profiler::TraceMe::ActivityEnd(id); } VLOG(3) << "TracingEnd " << id; void* __xla_cpu_runtime_AcquireInfeedBufferForDequeue( const xla::ExecutableRunOptions* run_options, int32_t buffer_length, const void* shape, int32_t shape_length) { return xla::cpu::runtime::AcquireInfeedBufferForDequeueImpl( run_options, buffer_length, shape, shape_length); } void __xla_cpu_runtime_ReleaseInfeedBufferAfterDequeue( const xla::ExecutableRunOptions* run_options, int32_t buffer_length, void* buffer_ptr, const void* shape_ptr, int32_t shape_length) { return xla::cpu::runtime::ReleaseInfeedBufferAfterDequeueImpl( run_options, buffer_length, buffer_ptr, shape_ptr, shape_length); } void* __xla_cpu_runtime_AcquireOutfeedBufferForPopulation( const xla::ExecutableRunOptions* run_options, int32_t buffer_length, const void* shape_ptr, int32_t shape_length) { return xla::cpu::runtime::AcquireOutfeedBufferForPopulationImpl( run_options, buffer_length, shape_ptr, shape_length); } void __xla_cpu_runtime_ReleaseOutfeedBufferAfterPopulation( const xla::ExecutableRunOptions* run_options, int32_t buffer_length, void* buffer_ptr, const void* shape_ptr, int32_t shape_length) { return xla::cpu::runtime::ReleaseOutfeedBufferAfterPopulationImpl( run_options, buffer_length, buffer_ptr, shape_ptr, shape_length); } void __xla_cpu_runtime_AllToAll(const xla::ExecutableRunOptions* run_options, int32_t channel_id_present, int64_t op_id, const void* replica_groups_str, int32_t replica_groups_str_size, int32_t num_buffers, int64_t buffer_size, void** source_buffers, void** destination_buffers) { return xla::cpu::runtime::AllToAllImpl( run_options, channel_id_present, op_id, replica_groups_str, replica_groups_str_size, num_buffers, buffer_size, source_buffers, destination_buffers); } void __xla_cpu_runtime_AllGather(const xla::ExecutableRunOptions* run_options, int32_t channel_id_present, int32_t use_global_device_ids, int64_t op_id, const void* replica_groups_str, int32_t replica_groups_str_size, int64_t buffer_size, void* source_buffer, void* destination_buffer) { return xla::cpu::runtime::AllGatherImpl( run_options, channel_id_present, use_global_device_ids, op_id, replica_groups_str, replica_groups_str_size, buffer_size, source_buffer, destination_buffer); } void __xla_cpu_runtime_ReduceScatter( const xla::ExecutableRunOptions* run_options, const void* replica_groups_str, int32_t replica_groups_str_size, int32_t channel_id_present, int32_t use_global_device_ids, int64_t op_id, int32_t reduction_kind, int32_t element_type, int64_t chunk_elems, void* input_buffer, void* output_buffer) { return xla::cpu::runtime::ReduceScatterImpl( run_options, replica_groups_str, replica_groups_str_size, channel_id_present, use_global_device_ids, op_id, reduction_kind, element_type, chunk_elems, input_buffer, output_buffer); } void __xla_cpu_runtime_AllReduce(const xla::ExecutableRunOptions* run_options, const void* replica_groups_str, int32_t replica_groups_str_size, int32_t channel_id_present, int32_t use_global_device_ids, int64_t op_id, int32_t reduction_kind, const void* shape_ptr, int32_t shape_length, int32_t num_buffers, void** input_buffers, void** output_buffers) { return xla::cpu::runtime::AllReduceImpl( run_options, replica_groups_str, replica_groups_str_size, channel_id_present, use_global_device_ids, op_id, reduction_kind, shape_ptr, shape_length, num_buffers, input_buffers, output_buffers); } void __xla_cpu_runtime_ReplicaId(const xla::ExecutableRunOptions* run_options, void* output_buffer) { return xla::cpu::runtime::ReplicaIdImpl(run_options, output_buffer); } void __xla_cpu_runtime_PartitionId(const xla::ExecutableRunOptions* run_options, void* output_buffer) { return xla::cpu::runtime::PartitionIdImpl(run_options, output_buffer); } void __xla_cpu_runtime_CollectivePermute( const xla::ExecutableRunOptions* run_options, int32_t channel_id_present, int64_t op_id, int32_t byte_size, void* input_buffer, void* output_buffer, const void* source_target_pairs, int32_t source_target_pairs_size) { return xla::cpu::runtime::CollectivePermuteImpl( run_options, channel_id_present, op_id, byte_size, input_buffer, output_buffer, source_target_pairs, source_target_pairs_size); }
#include "xla/service/cpu/cpu_runtime.h" #include <memory> #include <string> #include <tuple> #include "absl/strings/str_format.h" #include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive #include "xla/array2d.h" #include "xla/client/local_client.h" #include "xla/service/cpu/runtime_custom_call_status.h" #include "xla/service/cpu/runtime_matmul.h" #include "xla/service/cpu/runtime_matmul_acl.h" #include "xla/service/cpu/runtime_single_threaded_matmul.h" #include "xla/service/custom_call_status_internal.h" #include "xla/types.h" #include "tsl/platform/env.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class CpuRuntimeTest : public ::testing::Test {}; TEST_F(CpuRuntimeTest, FailureStatus) { XlaCustomCallStatus success_status; XlaCustomCallStatusSetFailure(&success_status, "Failed", 6); ASSERT_FALSE(__xla_cpu_runtime_StatusIsSuccess(&success_status)); }
CpuRuntimeTest_SuccessStatus
xla/service/cpu/cpu_runtime_test.cc
XfeedManager* GetXfeedManager(int device_ordinal) { static auto* managers = new absl::flat_hash_map<int, XfeedManager*>(); static absl::Mutex* mutex = new absl::Mutex(); absl::MutexLock lock(mutex); auto it = managers->find(device_ordinal); if (it == managers->end()) { it = managers->emplace(device_ordinal, new XfeedManager()).first; } return it->second; } absl::StatusOr<Shape> DecodeSelfDescribingShapeConstant(const void* shape_ptr, int32_t size_bytes) { ShapeProto shape_proto; if (!shape_proto.ParseFromArray(shape_ptr, size_bytes)) { return tsl::errors::Internal("Failed parsing the shape proto"); } Shape shape(shape_proto); auto status = ShapeUtil::ValidateShape(shape); if (!status.ok()) { return status; } return std::move(shape); } std::string ShapeString(const void* shape_ptr, int32_t shape_length) { absl::StatusOr<Shape> shape = DecodeSelfDescribingShapeConstant(shape_ptr, shape_length); if (shape.ok()) { return ShapeUtil::HumanStringWithLayout(shape.value()); } return "<invalid shape>"; } int GetDeviceOrdinal(const ExecutableRunOptions* run_options) { if (!run_options) { return 0; } else if (run_options->device_ordinal() != -1) { return run_options->device_ordinal(); } return run_options->stream()->parent()->device_ordinal(); } void* AcquireInfeedBufferForDequeueImpl(const ExecutableRunOptions* run_options, int32_t buffer_length, const void* shape, int32_t shape_length) { int device_ordinal = GetDeviceOrdinal(run_options); VLOG(2) << "AcquireInfeedBufferForDequeue: " << ShapeString(shape, shape_length) << " on stream executor " << device_ordinal; XfeedManager* xfeed = GetXfeedManager(device_ordinal); // Wait until there's a buffer to dequeue. XfeedBuffer* buffer = xfeed->infeed()->BlockingDequeueBuffer(); CHECK_EQ(buffer->length(), buffer_length) << "XLA program infeed request buffer size " << buffer_length << " did not match the runtime's infed buffer length " << buffer->length() << "; program reports desired shape: " << ShapeString(shape, shape_length); return buffer->data(); } VLOG(2) << "AcquireInfeedBufferForDequeue: " void ReleaseInfeedBufferAfterDequeueImpl( const ExecutableRunOptions* run_options, int32_t buffer_length, void* buffer_ptr, const void* shape_ptr, int32_t shape_length) { int device_ordinal = GetDeviceOrdinal(run_options); VLOG(2) << "ReleaseInfeedBufferAfterDeque: " << ShapeString(shape_ptr, shape_length) << " on stream executor " << device_ordinal; XfeedManager* xfeed = GetXfeedManager(device_ordinal); absl::StatusOr<Shape> shape = DecodeSelfDescribingShapeConstant(shape_ptr, shape_length); xfeed->infeed()->ReleaseCurrentBuffer(buffer_length, buffer_ptr, std::move(shape)); } VLOG(2) << "ReleaseInfeedBufferAfterDeque: " void* AcquireOutfeedBufferForPopulationImpl( const ExecutableRunOptions* run_options, int32_t buffer_length, const void* shape_ptr, int32_t shape_length) { int device_ordinal = GetDeviceOrdinal(run_options); VLOG(2) << "AcquireOutfeedBufferForPopulation: " << ShapeString(shape_ptr, shape_length) << " on stream executor " << device_ordinal; XfeedManager* xfeed = GetXfeedManager(device_ordinal); // Wait until there's a buffer to dequeue. XfeedBuffer* buffer = xfeed->outfeed()->BlockingDequeueBuffer(); CHECK_EQ(buffer->length(), buffer_length) << "XLA program outfeed request buffer size " << buffer_length << " did not match the runtime's outfeed buffer length " << buffer->length() << "; program reports outfed shape: " << ShapeString(shape_ptr, shape_length); return buffer->data(); } VLOG(2) << "AcquireOutfeedBufferForPopulation: " void ReleaseOutfeedBufferAfterPopulationImpl( const ExecutableRunOptions* run_options, int32_t buffer_length, void* buffer_ptr, const void* shape_ptr, int32_t shape_length) { int device_ordinal = GetDeviceOrdinal(run_options); VLOG(2) << "ReleaseOutfeedBufferAfterPopulation: " << ShapeString(shape_ptr, shape_length) << " on stream executor " << device_ordinal; XfeedManager* xfeed = GetXfeedManager(device_ordinal); absl::StatusOr<Shape> shape = DecodeSelfDescribingShapeConstant(shape_ptr, shape_length); xfeed->outfeed()->ReleaseCurrentBuffer(buffer_length, buffer_ptr, std::move(shape)); } VLOG(2) << "ReleaseOutfeedBufferAfterPopulation: " void ReplicaIdImpl(const ExecutableRunOptions* run_options, void* output_buffer) { int device_ordinal = GetDeviceOrdinal(run_options); int32_t replica_id = run_options->device_assignment() ->ReplicaIdForDevice(GlobalDeviceId(device_ordinal)) .value(); std::memcpy(output_buffer, &replica_id, 4); } void PartitionIdImpl(const ExecutableRunOptions* run_options, void* output_buffer) { int device_ordinal = GetDeviceOrdinal(run_options); const DeviceAssignment::LogicalID logical_id = run_options->device_assignment() ->LogicalIdForDevice(GlobalDeviceId(device_ordinal)) .value(); std::memcpy(output_buffer, &logical_id.computation_id, 4); } RendezvousKey GetRendezvousKey(const ExecutableRunOptions* run_options, GlobalDeviceId device, std::vector<ReplicaGroup> group, int32_t channel_id_present, std::optional<bool> use_global_device_ids, int64_t op_id) { const DeviceAssignment& device_assignment = *run_options->device_assignment(); RendezvousKey::CollectiveOpKind op_kind = channel_id_present ? RendezvousKey::kCrossModule : RendezvousKey::kCrossReplica; std::vector<GlobalDeviceId> participating_devices = GetParticipatingDevices(GlobalDeviceId(device), device_assignment, group, GetCollectiveOpGroupMode(channel_id_present != 0, use_global_device_ids) .value()) .value(); int num_local_participants = participating_devices.size(); return RendezvousKey{run_options->run_id(), std::move(participating_devices), num_local_participants, op_kind, op_id}; } CollectivesInterface* GetInProcessCollectivesImpl() { static InProcessCollectives* c = new InProcessCollectives(); return c; } CollectivesInterface* GetCollectivesImpl( const ExecutableRunOptions* run_options) { if (run_options->cpu_executable_run_options() && run_options->cpu_executable_run_options()->collectives()) { return run_options->cpu_executable_run_options()->collectives(); } return GetInProcessCollectivesImpl(); } absl::StatusOr<int> RankInGlobalDevices( absl::Span<GlobalDeviceId const> devices, GlobalDeviceId device) { auto it = absl::c_find(devices, device); if (it == devices.end()) { return InvalidArgument( "Device %d not present in global devices %s.", device.value(), absl::StrJoin(devices, ", ", [](std::string* out, GlobalDeviceId id) { absl::StrAppend(out, id.value()); })); } return std::distance(devices.begin(), it); } absl::StrJoin(devices, ", ", [](std::string* out, GlobalDeviceId id) { absl::StrAppend(out, id.value()); })); void AllToAllImpl(const ExecutableRunOptions* run_options, int32_t channel_id_present, int64_t op_id, const void* replica_groups_str, int32_t replica_groups_str_size, int32_t num_buffers, int64_t buffer_size, void** source_buffers, void** destination_buffers) { GlobalDeviceId device(GetDeviceOrdinal(run_options)); std::string_view replica_groups_serialized( static_cast<const char*>(replica_groups_str), replica_groups_str_size); std::vector<ReplicaGroup> group = ParseReplicaGroupsOnly(replica_groups_serialized).value(); RendezvousKey rendezvous_key = GetRendezvousKey(run_options, device, group, channel_id_present, /*use_global_device_ids=*/std::nullopt, op_id); int rank = RankInGlobalDevices(rendezvous_key.global_devices, device).value(); CollectivesInterface* collectives = GetCollectivesImpl(run_options); ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(source_buffers, sizeof(void*) * num_buffers); ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(destination_buffers, sizeof(void*) * num_buffers); auto communicator = collectives->GetCommunicator(rendezvous_key.global_devices, rank).value(); TF_CHECK_OK(communicator->AllToAll( rendezvous_key, buffer_size, absl::Span<const void* const>(source_buffers, num_buffers), absl::Span<void* const>(destination_buffers, num_buffers), DefaultCollectiveTimeout())); } void AllGatherImpl(const ExecutableRunOptions* run_options, int32_t channel_id_present, int32_t use_global_device_ids, int64_t op_id, const void* replica_groups_str, int32_t replica_groups_str_size, int64_t buffer_size, void* source_buffer, void* destination_buffer) { GlobalDeviceId device(GetDeviceOrdinal(run_options)); std::string_view replica_groups_serialized( static_cast<const char*>(replica_groups_str), replica_groups_str_size); std::vector<ReplicaGroup> group = ParseReplicaGroupsOnly(replica_groups_serialized).value(); RendezvousKey rendezvous_key = GetRendezvousKey(run_options, device, group, channel_id_present, use_global_device_ids, op_id); int rank = RankInGlobalDevices(rendezvous_key.global_devices, device).value(); CollectivesInterface* collectives = GetCollectivesImpl(run_options); auto communicator = collectives->GetCommunicator(rendezvous_key.global_devices, rank).value(); TF_CHECK_OK(communicator->AllGather(rendezvous_key, buffer_size, source_buffer, destination_buffer, DefaultCollectiveTimeout())); } void ReduceScatterImpl(const ExecutableRunOptions* run_options, const void* replica_groups_str, int32_t replica_groups_str_size, int32_t channel_id_present, int32_t use_global_device_ids, int64_t op_id, int32_t reduction_kind, int32_t element_type, int64_t chunk_elems, void* input_buffer, void* output_buffer) { GlobalDeviceId device(GetDeviceOrdinal(run_options)); std::string_view replica_groups_serialized( static_cast<const char*>(replica_groups_str), replica_groups_str_size); std::vector<ReplicaGroup> group = ParseReplicaGroupsOnly(replica_groups_serialized).value(); RendezvousKey rendezvous_key = GetRendezvousKey(run_options, device, group, channel_id_present, use_global_device_ids, op_id); int rank = RankInGlobalDevices(rendezvous_key.global_devices, device).value(); CollectivesInterface* collectives = GetCollectivesImpl(run_options); auto communicator = collectives->GetCommunicator(rendezvous_key.global_devices, rank).value(); TF_CHECK_OK(communicator->ReduceScatter( rendezvous_key, static_cast<ReductionKind>(reduction_kind), static_cast<PrimitiveType>(element_type), chunk_elems, input_buffer, output_buffer, DefaultCollectiveTimeout())); } void AllReduceImpl(const ExecutableRunOptions* run_options, const void* replica_groups_str, int32_t replica_groups_str_size, int32_t channel_id_present, int32_t use_global_device_ids, int64_t op_id, int32_t reduction_kind, const void* shape_ptr, int32_t shape_length, int32_t num_buffers, void** input_buffers, void** output_buffers) { GlobalDeviceId device(GetDeviceOrdinal(run_options)); std::string_view replica_groups_serialized( static_cast<const char*>(replica_groups_str), replica_groups_str_size); std::vector<ReplicaGroup> group = ParseReplicaGroupsOnly(replica_groups_serialized).value(); RendezvousKey rendezvous_key = GetRendezvousKey(run_options, device, group, channel_id_present, use_global_device_ids, op_id); auto shape_str = ShapeString(shape_ptr, shape_length); VLOG(2) << "All-reduce input/output shape : " << shape_str; Shape shape = DecodeSelfDescribingShapeConstant(shape_ptr, shape_length).value(); CHECK((num_buffers > 1 && shape.IsTuple()) || (num_buffers == 1 && LayoutUtil::IsDenseArray(shape))); int rank = RankInGlobalDevices(rendezvous_key.global_devices, device).value(); CollectivesInterface* collectives = GetCollectivesImpl(run_options); auto communicator = collectives->GetCommunicator(rendezvous_key.global_devices, rank).value(); for (int i = 0; i < num_buffers; i++) { Shape subshape = num_buffers == 1 ? shape : shape.tuple_shapes(i); TF_CHECK_OK(communicator->AllReduce( rendezvous_key, static_cast<ReductionKind>(reduction_kind), subshape.element_type(), ShapeUtil::ElementsIn(subshape), input_buffers[i], output_buffers[i], DefaultCollectiveTimeout())); } } VLOG(2) << "All-reduce input/output shape : " << shape_str; void CollectivePermuteImpl(const ExecutableRunOptions* run_options, int32_t channel_id_present, int64_t op_id, int32_t byte_size, void* input_buffer, void* output_buffer, const void* source_target_pairs, int32_t source_target_pairs_size) { GlobalDeviceId device(GetDeviceOrdinal(run_options)); std::string_view source_target_pairs_serialized( static_cast<const char*>(source_target_pairs), source_target_pairs_size); auto pairs = absl::StrSplit(source_target_pairs_serialized, ','); const DeviceAssignment::LogicalID logical_id = run_options->device_assignment()->LogicalIdForDevice(device).value(); int32_t logical_device_id = channel_id_present ? logical_id.computation_id : logical_id.replica_id; std::optional<int> source_replica_id; std::vector<int> copy_to; for (auto& p : pairs) { std::vector<std::string> mapping = absl::StrSplit(p, '='); CHECK_EQ(mapping.size(), 2); int from = std::stoi(mapping[0]); int to = std::stoi(mapping[1]); if (from == logical_device_id) { copy_to.push_back(to); } if (to == logical_device_id) { CHECK(!source_replica_id.has_value()); source_replica_id = from; } } RendezvousKey rendezvous_key = GetRendezvousKey(run_options, device, {}, channel_id_present, /*use_global_device_ids=*/std::nullopt, op_id); int rank = RankInGlobalDevices(rendezvous_key.global_devices, device).value(); CollectivesInterface* collectives = GetCollectivesImpl(run_options); auto communicator = collectives->GetCommunicator(rendezvous_key.global_devices, rank).value(); TF_CHECK_OK(communicator->CollectivePermute( rendezvous_key, byte_size, source_replica_id, copy_to, input_buffer, output_buffer, DefaultCollectiveTimeout())); } ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY int __xla_cpu_runtime_PrintfToStderr( const char* format, ...) { VLOG(3) << "__xla_cpu_runtime_PrintfToStderr " << format; va_list args; va_start(args, format); int result = vfprintf(stderr, format, args); va_end(args); return result; } VLOG(3) << "__xla_cpu_runtime_PrintfToStderr " << format; ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY int64_t __xla_cpu_runtime_TracingStart( const void* /* ExecutableRunOptions* run_options_ptr*/, const char* name, const char* hlo_module, int64_t program_id) { VLOG(3) << "TracingStart " << name; auto trace_in = tsl::profiler::TraceMeEncode(name, {{"hlo_op", name}, {"hlo_module", hlo_module}, {"program_id", program_id}}); return tsl::profiler::TraceMe::ActivityStart(trace_in); } VLOG(3) << "TracingStart " << name; ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_TracingEnd( const void* /* ExecutableRunOptions* run_options_ptr*/, int64_t id) { VLOG(3) << "TracingEnd " << id; tsl::profiler::TraceMe::ActivityEnd(id); } VLOG(3) << "TracingEnd " << id; void* __xla_cpu_runtime_AcquireInfeedBufferForDequeue( const xla::ExecutableRunOptions* run_options, int32_t buffer_length, const void* shape, int32_t shape_length) { return xla::cpu::runtime::AcquireInfeedBufferForDequeueImpl( run_options, buffer_length, shape, shape_length); } void __xla_cpu_runtime_ReleaseInfeedBufferAfterDequeue( const xla::ExecutableRunOptions* run_options, int32_t buffer_length, void* buffer_ptr, const void* shape_ptr, int32_t shape_length) { return xla::cpu::runtime::ReleaseInfeedBufferAfterDequeueImpl( run_options, buffer_length, buffer_ptr, shape_ptr, shape_length); } void* __xla_cpu_runtime_AcquireOutfeedBufferForPopulation( const xla::ExecutableRunOptions* run_options, int32_t buffer_length, const void* shape_ptr, int32_t shape_length) { return xla::cpu::runtime::AcquireOutfeedBufferForPopulationImpl( run_options, buffer_length, shape_ptr, shape_length); } void __xla_cpu_runtime_ReleaseOutfeedBufferAfterPopulation( const xla::ExecutableRunOptions* run_options, int32_t buffer_length, void* buffer_ptr, const void* shape_ptr, int32_t shape_length) { return xla::cpu::runtime::ReleaseOutfeedBufferAfterPopulationImpl( run_options, buffer_length, buffer_ptr, shape_ptr, shape_length); } void __xla_cpu_runtime_AllToAll(const xla::ExecutableRunOptions* run_options, int32_t channel_id_present, int64_t op_id, const void* replica_groups_str, int32_t replica_groups_str_size, int32_t num_buffers, int64_t buffer_size, void** source_buffers, void** destination_buffers) { return xla::cpu::runtime::AllToAllImpl( run_options, channel_id_present, op_id, replica_groups_str, replica_groups_str_size, num_buffers, buffer_size, source_buffers, destination_buffers); } void __xla_cpu_runtime_AllGather(const xla::ExecutableRunOptions* run_options, int32_t channel_id_present, int32_t use_global_device_ids, int64_t op_id, const void* replica_groups_str, int32_t replica_groups_str_size, int64_t buffer_size, void* source_buffer, void* destination_buffer) { return xla::cpu::runtime::AllGatherImpl( run_options, channel_id_present, use_global_device_ids, op_id, replica_groups_str, replica_groups_str_size, buffer_size, source_buffer, destination_buffer); } void __xla_cpu_runtime_ReduceScatter( const xla::ExecutableRunOptions* run_options, const void* replica_groups_str, int32_t replica_groups_str_size, int32_t channel_id_present, int32_t use_global_device_ids, int64_t op_id, int32_t reduction_kind, int32_t element_type, int64_t chunk_elems, void* input_buffer, void* output_buffer) { return xla::cpu::runtime::ReduceScatterImpl( run_options, replica_groups_str, replica_groups_str_size, channel_id_present, use_global_device_ids, op_id, reduction_kind, element_type, chunk_elems, input_buffer, output_buffer); } void __xla_cpu_runtime_AllReduce(const xla::ExecutableRunOptions* run_options, const void* replica_groups_str, int32_t replica_groups_str_size, int32_t channel_id_present, int32_t use_global_device_ids, int64_t op_id, int32_t reduction_kind, const void* shape_ptr, int32_t shape_length, int32_t num_buffers, void** input_buffers, void** output_buffers) { return xla::cpu::runtime::AllReduceImpl( run_options, replica_groups_str, replica_groups_str_size, channel_id_present, use_global_device_ids, op_id, reduction_kind, shape_ptr, shape_length, num_buffers, input_buffers, output_buffers); } void __xla_cpu_runtime_ReplicaId(const xla::ExecutableRunOptions* run_options, void* output_buffer) { return xla::cpu::runtime::ReplicaIdImpl(run_options, output_buffer); } void __xla_cpu_runtime_PartitionId(const xla::ExecutableRunOptions* run_options, void* output_buffer) { return xla::cpu::runtime::PartitionIdImpl(run_options, output_buffer); } void __xla_cpu_runtime_CollectivePermute( const xla::ExecutableRunOptions* run_options, int32_t channel_id_present, int64_t op_id, int32_t byte_size, void* input_buffer, void* output_buffer, const void* source_target_pairs, int32_t source_target_pairs_size) { return xla::cpu::runtime::CollectivePermuteImpl( run_options, channel_id_present, op_id, byte_size, input_buffer, output_buffer, source_target_pairs, source_target_pairs_size); }
#include "xla/service/cpu/cpu_runtime.h" #include <memory> #include <string> #include <tuple> #include "absl/strings/str_format.h" #include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive #include "xla/array2d.h" #include "xla/client/local_client.h" #include "xla/service/cpu/runtime_custom_call_status.h" #include "xla/service/cpu/runtime_matmul.h" #include "xla/service/cpu/runtime_matmul_acl.h" #include "xla/service/cpu/runtime_single_threaded_matmul.h" #include "xla/service/custom_call_status_internal.h" #include "xla/types.h" #include "tsl/platform/env.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class CpuRuntimeTest : public ::testing::Test {}; TEST_F(CpuRuntimeTest, SuccessStatus) { XlaCustomCallStatus success_status; // Success is the default state. ASSERT_TRUE(__xla_cpu_runtime_StatusIsSuccess(&success_status)); }
GraphCyclesTest_CanContractEdge
xla/service/graphcycles/graphcycles_test.cc
GraphCycles::GraphCycles() : rep_(new Rep) {} GraphCycles::~GraphCycles() { delete rep_; } bool GraphCycles::CheckInvariants() const { Rep* r = rep_; NodeSet ranks; // Set of ranks seen so far. for (size_t x = 0; x < r->nodes_.size(); x++) { Node* nx = &r->nodes_[x]; if (nx->visited) { LOG(FATAL) << "Did not clear visited marker on node " << x; } if (!ranks.insert(nx->rank).second) { LOG(FATAL) << "Duplicate occurrence of rank " << nx->rank; } NodeIO* nx_io = &r->node_io_[x]; for (int32_t y : nx_io->out.GetSequence()) { Node* ny = &r->nodes_[y]; if (nx->rank >= ny->rank) { LOG(FATAL) << "Edge " << x << "->" << y << " has bad rank assignment " << nx->rank << "->" << ny->rank; } } } return true; } int32_t GraphCycles::NewNode() { if (rep_->free_nodes_.empty()) { Node n; n.visited = false; n.rank = rep_->nodes_.size(); rep_->nodes_.emplace_back(n); rep_->node_io_.emplace_back(); rep_->node_data_.push_back(nullptr); return n.rank; } else { // Preserve preceding rank since the set of ranks in use must be // a permutation of [0,rep_->nodes_.size()-1]. int32_t r = rep_->free_nodes_.back(); rep_->free_nodes_.pop_back(); rep_->node_data_[r] = nullptr; return r; } } void GraphCycles::RemoveNode(int32_t node) { NodeIO* x = &rep_->node_io_[node]; for (int32_t y : x->out.GetSequence()) { rep_->node_io_[y].in.Erase(node); } for (int32_t y : x->in.GetSequence()) { rep_->node_io_[y].out.Erase(node); } x->in.Clear(); x->out.Clear(); rep_->free_nodes_.push_back(node); } void* GraphCycles::GetNodeData(int32_t node) const { return rep_->node_data_[node]; } void GraphCycles::SetNodeData(int32_t node, void* data) { rep_->node_data_[node] = data; } bool GraphCycles::HasEdge(int32_t x, int32_t y) const { return rep_->node_io_[x].out.Contains(y); } void GraphCycles::RemoveEdge(int32_t x, int32_t y) { rep_->node_io_[x].out.Erase(y); rep_->node_io_[y].in.Erase(x); // No need to update the rank assignment since a previous valid // rank assignment remains valid after an edge deletion. } bool GraphCycles::InsertEdge(int32_t x, int32_t y) { if (x == y) return false; Rep* r = rep_; NodeIO* nx_io = &r->node_io_[x]; if (!nx_io->out.Insert(y)) { // Edge already exists. return true; } NodeIO* ny_io = &r->node_io_[y]; ny_io->in.Insert(x); Node* nx = &r->nodes_[x]; Node* ny = &r->nodes_[y]; if (nx->rank <= ny->rank) { // New edge is consistent with existing rank assignment. return true; } // Current rank assignments are incompatible with the new edge. Recompute. // We only need to consider nodes that fall in the range [ny->rank,nx->rank]. if (!ForwardDFS(r, y, nx->rank)) { // Found a cycle. Undo the insertion and tell caller. nx_io->out.Erase(y); ny_io->in.Erase(x); // Since we do not call Reorder() on this path, clear any visited // markers left by ForwardDFS. ClearVisitedBits(r, r->deltaf_); return false; } BackwardDFS(r, x, ny->rank); Reorder(r); return true; } static bool ForwardDFS(GraphCycles::Rep* r, int32_t n, int32_t upper_bound) { // Avoid recursion since stack space might be limited. // We instead keep a stack of nodes to visit. r->deltaf_.clear(); r->stack_.clear(); r->stack_.push_back(n); while (!r->stack_.empty()) { n = r->stack_.back(); r->stack_.pop_back(); Node* nn = &r->nodes_[n]; if (nn->visited) continue; nn->visited = true; r->deltaf_.push_back(n); NodeIO* nn_io = &r->node_io_[n]; for (auto w : nn_io->out.GetSequence()) { Node* nw = &r->nodes_[w]; if (nw->rank == upper_bound) { return false; // Cycle } if (!nw->visited && nw->rank < upper_bound) { r->stack_.push_back(w); } } } return true; } static void BackwardDFS(GraphCycles::Rep* r, int32_t n, int32_t lower_bound) { r->deltab_.clear(); r->stack_.clear(); r->stack_.push_back(n); while (!r->stack_.empty()) { n = r->stack_.back(); r->stack_.pop_back(); Node* nn = &r->nodes_[n]; if (nn->visited) continue; nn->visited = true; r->deltab_.push_back(n); NodeIO* nn_io = &r->node_io_[n]; for (auto w : nn_io->in.GetSequence()) { Node* nw = &r->nodes_[w]; if (!nw->visited && lower_bound < nw->rank) { r->stack_.push_back(w); } } } } static void Reorder(GraphCycles::Rep* r) { Sort(r->nodes_, &r->deltab_); Sort(r->nodes_, &r->deltaf_); // Adds contents of delta lists to list_ (backwards deltas first). r->list_.clear(); MoveToList(r, &r->deltab_, &r->list_); MoveToList(r, &r->deltaf_, &r->list_); // Produce sorted list of all ranks that will be reassigned. r->merged_.resize(r->deltab_.size() + r->deltaf_.size()); std::merge(r->deltab_.begin(), r->deltab_.end(), r->deltaf_.begin(), r->deltaf_.end(), r->merged_.begin()); // Assign the ranks in order to the collected list. for (size_t i = 0; i < r->list_.size(); i++) { r->nodes_[r->list_[i]].rank = r->merged_[i]; } } static void Sort(absl::Span<const Node> nodes, std::vector<int32_t>* delta) { std::sort(delta->begin(), delta->end(), [&](int32_t a, int32_t b) { return nodes[a].rank < nodes[b].rank; }); } static void MoveToList(GraphCycles::Rep* r, std::vector<int32_t>* src, std::vector<int32_t>* dst) { for (size_t i = 0; i < src->size(); i++) { int32_t w = (*src)[i]; (*src)[i] = r->nodes_[w].rank; // Replace src entry with its rank r->nodes_[w].visited = false; // Prepare for future DFS calls dst->push_back(w); } } static void ClearVisitedBits(GraphCycles::Rep* r, absl::Span<const int32_t> visited_indices) { for (auto index : visited_indices) { r->nodes_[index].visited = false; } } int GraphCycles::FindPath(int32_t x, int32_t y, int max_path_len, int32_t path[]) const { // Forward depth first search starting at x until we hit y. // As we descend into a node, we push it onto the path. // As we leave a node, we remove it from the path. int path_len = 0; Rep* r = rep_; NodeSet seen; r->stack_.clear(); r->stack_.push_back(x); while (!r->stack_.empty()) { int32_t n = r->stack_.back(); r->stack_.pop_back(); if (n < 0) { // Marker to indicate that we are leaving a node path_len--; continue; } if (path_len < max_path_len) { path[path_len] = n; } path_len++; r->stack_.push_back(-1); // Will remove tentative path entry if (n == y) { return path_len; } for (auto w : r->node_io_[n].out.GetSequence()) { if (seen.insert(w).second) { r->stack_.push_back(w); } } } return 0; } bool GraphCycles::IsReachable(int32_t x, int32_t y) const { return FindPath(x, y, 0, nullptr) > 0; } bool GraphCycles::IsReachableNonConst(int32_t x, int32_t y) { if (x == y) return true; Rep* r = rep_; Node* nx = &r->nodes_[x]; Node* ny = &r->nodes_[y]; if (nx->rank >= ny->rank) { // x cannot reach y since it is after it in the topological ordering return false; } // See if x can reach y using a DFS search that is limited to y's rank bool reachable = !ForwardDFS(r, x, ny->rank); // Clear any visited markers left by ForwardDFS. ClearVisitedBits(r, r->deltaf_); return reachable; } bool GraphCycles::CanContractEdge(int32_t a, int32_t b) { CHECK(HasEdge(a, b)) << "No edge exists from " << a << " to " << b; RemoveEdge(a, b); bool reachable = IsReachableNonConst(a, b); // Restore the graph to its original state. InsertEdge(a, b); // If reachable, then contracting edge will cause cycle. return !reachable; } std::optional<int32_t> GraphCycles::ContractEdge(int32_t a, int32_t b) { CHECK(HasEdge(a, b)); RemoveEdge(a, b); if (IsReachableNonConst(a, b)) { // Restore the graph to its original state. InsertEdge(a, b); return std::nullopt; } if (rep_->node_io_[b].in.Size() + rep_->node_io_[b].out.Size() > rep_->node_io_[a].in.Size() + rep_->node_io_[a].out.Size()) { // Swap "a" and "b" to minimize copying. std::swap(a, b); } NodeIO* nb_io = &rep_->node_io_[b]; OrderedNodeSet out = std::move(nb_io->out); OrderedNodeSet in = std::move(nb_io->in); for (int32_t y : out.GetSequence()) { rep_->node_io_[y].in.Erase(b); } for (int32_t y : in.GetSequence()) { rep_->node_io_[y].out.Erase(b); } rep_->free_nodes_.push_back(b); rep_->node_io_[a].out.Reserve(rep_->node_io_[a].out.Size() + out.Size()); for (int32_t y : out.GetSequence()) { InsertEdge(a, y); } rep_->node_io_[a].in.Reserve(rep_->node_io_[a].in.Size() + in.Size()); for (int32_t y : in.GetSequence()) { InsertEdge(y, a); } // Note, if the swap happened it might be what originally was called "b". return a; } absl::Span<const int32_t> GraphCycles::Successors(int32_t node) const { return rep_->node_io_[node].out.GetSequence(); } absl::Span<const int32_t> GraphCycles::Predecessors(int32_t node) const { return rep_->node_io_[node].in.GetSequence(); } std::vector<int32_t> GraphCycles::SuccessorsCopy(int32_t node) const { absl::Span<const int32_t> successors = Successors(node); return std::vector<int32_t>(successors.begin(), successors.end()); } std::vector<int32_t> GraphCycles::PredecessorsCopy(int32_t node) const { absl::Span<const int32_t> predecessors = Predecessors(node); return std::vector<int32_t>(predecessors.begin(), predecessors.end()); } std::vector<int32_t> GraphCycles::AllNodesInPostOrder() const { absl::flat_hash_set<int32_t> free_nodes_set; absl::c_copy(rep_->free_nodes_, std::inserter(free_nodes_set, free_nodes_set.begin())); std::vector<int32_t> all_nodes; all_nodes.reserve(rep_->nodes_.size() - free_nodes_set.size()); for (int64_t i = 0, e = rep_->nodes_.size(); i < e; i++) { if (!free_nodes_set.contains(i)) { all_nodes.push_back(i); } } SortInPostOrder(rep_->nodes_, &all_nodes); return all_nodes; } std::string GraphCycles::DebugString() const { absl::flat_hash_set<int32_t> free_nodes_set(rep_->free_nodes_.begin(), rep_->free_nodes_.end()); std::string result = "digraph {\n"; for (int i = 0, end = rep_->nodes_.size(); i < end; i++) { if (free_nodes_set.contains(i)) { continue; } for (int32_t succ : rep_->node_io_[i].out.GetSequence()) { absl::StrAppend(&result, " \"", i, "\" -> \"", succ, "\"\n"); } } absl::StrAppend(&result, "}\n"); return result; }
#include "xla/service/graphcycles/graphcycles.h" #include <cstdint> #include <optional> #include <random> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/random/random.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" class GraphCyclesTest : public ::testing::Test { public: tensorflow::GraphCycles g_; // Test relies on ith NewNode() call returning Node numbered i GraphCyclesTest() { for (int i = 0; i < 100; i++) { CHECK_EQ(i, g_.NewNode()); } CHECK(g_.CheckInvariants()); } bool AddEdge(int x, int y) { return g_.InsertEdge(x, y); } void AddMultiples() { // For every node x > 0: add edge to 2*x, 3*x for (int x = 1; x < 25; x++) { EXPECT_TRUE(AddEdge(x, 2 * x)) << x; EXPECT_TRUE(AddEdge(x, 3 * x)) << x; } CHECK(g_.CheckInvariants()); } std::string Path(int x, int y) { static const int kPathSize = 5; int32_t path[kPathSize]; int np = g_.FindPath(x, y, kPathSize, path); std::string result; for (int i = 0; i < np; i++) { if (i >= kPathSize) { result += " ..."; break; } if (!result.empty()) result.push_back(' '); char buf[20]; snprintf(buf, sizeof(buf), "%d", path[i]); result += buf; } return result; } }; TEST_F(GraphCyclesTest, CanContractEdge) { ASSERT_TRUE(AddEdge(1, 2)); ASSERT_TRUE(AddEdge(1, 3)); ASSERT_TRUE(AddEdge(2, 3)); ASSERT_TRUE(AddEdge(2, 4)); ASSERT_TRUE(AddEdge(3, 4)); EXPECT_FALSE(g_.CanContractEdge(1, 3)); EXPECT_FALSE(g_.CanContractEdge(2, 4)); EXPECT_TRUE(g_.CanContractEdge(1, 2)); EXPECT_TRUE(g_.CanContractEdge(2, 3)); EXPECT_TRUE(g_.CanContractEdge(3, 4)); }
DynamicDimensionSimplifierTest_BroadcastReshapeForwarding
xla/service/dynamic_dimension_simplifier_test.cc
absl::StatusOr<bool> ConcatForwarding(HloInstruction* concat) { if (concat->opcode() != HloOpcode::kConcatenate) { return false; } bool changed = false; auto parent = concat->parent(); std::vector<HloInstruction*> new_operands; for (HloInstruction* operand : concat->operands()) { if (operand->opcode() != HloOpcode::kConcatenate || operand->concatenate_dimension() != concat->concatenate_dimension()) { new_operands.push_back(operand); } else { changed = true; for (HloInstruction* operand_operand : operand->operands()) { new_operands.push_back(operand_operand); } } } if (changed) { auto new_concat = parent->AddInstruction(HloInstruction::CreateConcatenate( concat->shape(), new_operands, concat->concatenate_dimension())); TF_RETURN_IF_ERROR(parent->ReplaceInstruction(concat, new_concat)); } return changed; } absl::StatusOr<bool> SliceConcatForwarding(HloInstruction* slice) { if (slice->opcode() != HloOpcode::kSlice) { return false; } auto concat = slice->mutable_operand(0); if (concat->opcode() != HloOpcode::kConcatenate) { return false; } if (slice->shape().rank() != 1) { // Slice concat forwarding only work for size 1 tensor. return false; } int64_t concat_dim = concat->concatenate_dimension(); std::vector<HloInstruction*> new_operands; int64_t size_so_far = 0; int64_t slice_size = slice->shape().dimensions(concat_dim); if (slice_size != slice->slice_limits(0) - slice->slice_starts(0)) { return false; } if (slice->slice_strides(0) != 1) { return false; } for (HloInstruction* operand : concat->operands()) { if (size_so_far == slice->slice_starts(0) && operand->shape().dimensions(0) == slice_size) { // Found an operand that can be forwarded. TF_RETURN_IF_ERROR(slice->ReplaceAllUsesWith(operand)); return true; } size_so_far += operand->shape().dimensions(concat_dim); } return false; } absl::StatusOr<bool> ReshapeBroadcastForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto broadcast = reshape->mutable_operand(0); if (broadcast->opcode() != HloOpcode::kBroadcast) { return false; } if (reshape->shape().rank() != 0) { return false; } if (broadcast->shape().rank() != 1) { return false; } if (broadcast->mutable_operand(0)->shape().rank() != 0) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(broadcast->mutable_operand(0))); return true; } absl::StatusOr<bool> ReshapeReshapeForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto reshape_2 = reshape->mutable_operand(0); if (reshape_2->opcode() != HloOpcode::kReshape) { return false; } if (!Shape::Equal()(reshape->shape(), reshape_2->operand(0)->shape())) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(reshape_2->mutable_operand(0))); return true; } absl::StatusOr<bool> IdentityConvertRemoving(HloInstruction* convert) { if (convert->opcode() != HloOpcode::kConvert) { return false; } auto operand = convert->mutable_operand(0); if (Shape::Equal()(convert->shape(), operand->shape())) { TF_RETURN_IF_ERROR(convert->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> IdentityReshapeRemoving(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto operand = reshape->mutable_operand(0); if (Shape::Equal()(reshape->shape(), operand->shape())) { TF_RETURN_IF_ERROR(reshape->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> DynamicDimensionSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), before:\n" + module->ToString()); bool changed = false; for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, SliceConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeBroadcastForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeReshapeForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityConvertRemoving(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityReshapeRemoving(inst)); changed |= local_changed; } } XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), after:\n" + module->ToString()); return changed; } XLA_VLOG_LINES( XLA_VLOG_LINES(
#include "xla/service/dynamic_dimension_simplifier.h" #include <memory> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.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/layout_util.h" #include "xla/literal.h" #include "xla/service/hlo_creation_utils.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_fix.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/service/shape_inference.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" class DynamicDimensionSimplifierTest : public HloTestBase {}; TEST_F(DynamicDimensionSimplifierTest, BroadcastReshapeForwarding) { const char* kModuleStr = R"( HloModule m test { p0 = s32[] parameter(0) broadcast = s32[1] broadcast(p0), dimensions={} ROOT reshape = s32[] reshape(broadcast) } )"; TF_ASSERT_OK_AND_ASSIGN(auto m, ParseAndReturnVerifiedModule(kModuleStr)); DynamicDimensionSimplifier simplifier; ASSERT_TRUE(simplifier.Run(m.get()).value()); EXPECT_THAT(m->entry_computation()->root_instruction(), GmockMatch(m::Parameter(0))); }
DynamicDimensionSimplifierTest_DoNotForwardConcatMultipleDims
xla/service/dynamic_dimension_simplifier_test.cc
absl::StatusOr<bool> ConcatForwarding(HloInstruction* concat) { if (concat->opcode() != HloOpcode::kConcatenate) { return false; } bool changed = false; auto parent = concat->parent(); std::vector<HloInstruction*> new_operands; for (HloInstruction* operand : concat->operands()) { if (operand->opcode() != HloOpcode::kConcatenate || operand->concatenate_dimension() != concat->concatenate_dimension()) { new_operands.push_back(operand); } else { changed = true; for (HloInstruction* operand_operand : operand->operands()) { new_operands.push_back(operand_operand); } } } if (changed) { auto new_concat = parent->AddInstruction(HloInstruction::CreateConcatenate( concat->shape(), new_operands, concat->concatenate_dimension())); TF_RETURN_IF_ERROR(parent->ReplaceInstruction(concat, new_concat)); } return changed; } absl::StatusOr<bool> SliceConcatForwarding(HloInstruction* slice) { if (slice->opcode() != HloOpcode::kSlice) { return false; } auto concat = slice->mutable_operand(0); if (concat->opcode() != HloOpcode::kConcatenate) { return false; } if (slice->shape().rank() != 1) { // Slice concat forwarding only work for size 1 tensor. return false; } int64_t concat_dim = concat->concatenate_dimension(); std::vector<HloInstruction*> new_operands; int64_t size_so_far = 0; int64_t slice_size = slice->shape().dimensions(concat_dim); if (slice_size != slice->slice_limits(0) - slice->slice_starts(0)) { return false; } if (slice->slice_strides(0) != 1) { return false; } for (HloInstruction* operand : concat->operands()) { if (size_so_far == slice->slice_starts(0) && operand->shape().dimensions(0) == slice_size) { // Found an operand that can be forwarded. TF_RETURN_IF_ERROR(slice->ReplaceAllUsesWith(operand)); return true; } size_so_far += operand->shape().dimensions(concat_dim); } return false; } absl::StatusOr<bool> ReshapeBroadcastForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto broadcast = reshape->mutable_operand(0); if (broadcast->opcode() != HloOpcode::kBroadcast) { return false; } if (reshape->shape().rank() != 0) { return false; } if (broadcast->shape().rank() != 1) { return false; } if (broadcast->mutable_operand(0)->shape().rank() != 0) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(broadcast->mutable_operand(0))); return true; } absl::StatusOr<bool> ReshapeReshapeForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto reshape_2 = reshape->mutable_operand(0); if (reshape_2->opcode() != HloOpcode::kReshape) { return false; } if (!Shape::Equal()(reshape->shape(), reshape_2->operand(0)->shape())) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(reshape_2->mutable_operand(0))); return true; } absl::StatusOr<bool> IdentityConvertRemoving(HloInstruction* convert) { if (convert->opcode() != HloOpcode::kConvert) { return false; } auto operand = convert->mutable_operand(0); if (Shape::Equal()(convert->shape(), operand->shape())) { TF_RETURN_IF_ERROR(convert->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> IdentityReshapeRemoving(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto operand = reshape->mutable_operand(0); if (Shape::Equal()(reshape->shape(), operand->shape())) { TF_RETURN_IF_ERROR(reshape->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> DynamicDimensionSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), before:\n" + module->ToString()); bool changed = false; for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, SliceConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeBroadcastForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeReshapeForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityConvertRemoving(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityReshapeRemoving(inst)); changed |= local_changed; } } XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), after:\n" + module->ToString()); return changed; } XLA_VLOG_LINES( XLA_VLOG_LINES(
#include "xla/service/dynamic_dimension_simplifier.h" #include <memory> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.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/layout_util.h" #include "xla/literal.h" #include "xla/service/hlo_creation_utils.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_fix.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/service/shape_inference.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" class DynamicDimensionSimplifierTest : public HloTestBase {}; TEST_F(DynamicDimensionSimplifierTest, DoNotForwardConcatMultipleDims) { const char* kModuleStr = R"( HloModule m test { p0 = s32[1, 1] parameter(0) p1 = s32[1, 1] parameter(1) p2 = s32[2, 1] parameter(2) concat1 = s32[2, 1] concatenate(p0, p1), dimensions={0} ROOT concat2 = s32[2, 2] concatenate(concat1, p2), dimensions={1} } )"; TF_ASSERT_OK_AND_ASSIGN(auto m, ParseAndReturnVerifiedModule(kModuleStr)); DynamicDimensionSimplifier simplifier; ASSERT_FALSE(simplifier.Run(m.get()).value()); }
DynamicDimensionSimplifierTest_DoNotForwardConcatSliceSizeMismatch
xla/service/dynamic_dimension_simplifier_test.cc
absl::StatusOr<bool> ConcatForwarding(HloInstruction* concat) { if (concat->opcode() != HloOpcode::kConcatenate) { return false; } bool changed = false; auto parent = concat->parent(); std::vector<HloInstruction*> new_operands; for (HloInstruction* operand : concat->operands()) { if (operand->opcode() != HloOpcode::kConcatenate || operand->concatenate_dimension() != concat->concatenate_dimension()) { new_operands.push_back(operand); } else { changed = true; for (HloInstruction* operand_operand : operand->operands()) { new_operands.push_back(operand_operand); } } } if (changed) { auto new_concat = parent->AddInstruction(HloInstruction::CreateConcatenate( concat->shape(), new_operands, concat->concatenate_dimension())); TF_RETURN_IF_ERROR(parent->ReplaceInstruction(concat, new_concat)); } return changed; } absl::StatusOr<bool> SliceConcatForwarding(HloInstruction* slice) { if (slice->opcode() != HloOpcode::kSlice) { return false; } auto concat = slice->mutable_operand(0); if (concat->opcode() != HloOpcode::kConcatenate) { return false; } if (slice->shape().rank() != 1) { // Slice concat forwarding only work for size 1 tensor. return false; } int64_t concat_dim = concat->concatenate_dimension(); std::vector<HloInstruction*> new_operands; int64_t size_so_far = 0; int64_t slice_size = slice->shape().dimensions(concat_dim); if (slice_size != slice->slice_limits(0) - slice->slice_starts(0)) { return false; } if (slice->slice_strides(0) != 1) { return false; } for (HloInstruction* operand : concat->operands()) { if (size_so_far == slice->slice_starts(0) && operand->shape().dimensions(0) == slice_size) { // Found an operand that can be forwarded. TF_RETURN_IF_ERROR(slice->ReplaceAllUsesWith(operand)); return true; } size_so_far += operand->shape().dimensions(concat_dim); } return false; } absl::StatusOr<bool> ReshapeBroadcastForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto broadcast = reshape->mutable_operand(0); if (broadcast->opcode() != HloOpcode::kBroadcast) { return false; } if (reshape->shape().rank() != 0) { return false; } if (broadcast->shape().rank() != 1) { return false; } if (broadcast->mutable_operand(0)->shape().rank() != 0) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(broadcast->mutable_operand(0))); return true; } absl::StatusOr<bool> ReshapeReshapeForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto reshape_2 = reshape->mutable_operand(0); if (reshape_2->opcode() != HloOpcode::kReshape) { return false; } if (!Shape::Equal()(reshape->shape(), reshape_2->operand(0)->shape())) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(reshape_2->mutable_operand(0))); return true; } absl::StatusOr<bool> IdentityConvertRemoving(HloInstruction* convert) { if (convert->opcode() != HloOpcode::kConvert) { return false; } auto operand = convert->mutable_operand(0); if (Shape::Equal()(convert->shape(), operand->shape())) { TF_RETURN_IF_ERROR(convert->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> IdentityReshapeRemoving(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto operand = reshape->mutable_operand(0); if (Shape::Equal()(reshape->shape(), operand->shape())) { TF_RETURN_IF_ERROR(reshape->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> DynamicDimensionSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), before:\n" + module->ToString()); bool changed = false; for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, SliceConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeBroadcastForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeReshapeForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityConvertRemoving(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityReshapeRemoving(inst)); changed |= local_changed; } } XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), after:\n" + module->ToString()); return changed; } XLA_VLOG_LINES( XLA_VLOG_LINES(
#include "xla/service/dynamic_dimension_simplifier.h" #include <memory> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.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/layout_util.h" #include "xla/literal.h" #include "xla/service/hlo_creation_utils.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_fix.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/service/shape_inference.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" class DynamicDimensionSimplifierTest : public HloTestBase {}; TEST_F(DynamicDimensionSimplifierTest, DoNotForwardConcatSliceSizeMismatch) { const char* kModuleStr = R"( HloModule m test { p0 = s32[1] parameter(0) p1 = s32[1] parameter(1) p2 = s32[1] parameter(2) concat = s32[3] concatenate(p0, p1, p2), dimensions={0} ROOT slice = s32[2] slice(concat), slice={[1:3]} } )"; TF_ASSERT_OK_AND_ASSIGN(auto m, ParseAndReturnVerifiedModule(kModuleStr)); DynamicDimensionSimplifier simplifier; ASSERT_FALSE(simplifier.Run(m.get()).value()); }
DynamicDimensionSimplifierTest_DoNotForwardConcatSliceStrided
xla/service/dynamic_dimension_simplifier_test.cc
absl::StatusOr<bool> ConcatForwarding(HloInstruction* concat) { if (concat->opcode() != HloOpcode::kConcatenate) { return false; } bool changed = false; auto parent = concat->parent(); std::vector<HloInstruction*> new_operands; for (HloInstruction* operand : concat->operands()) { if (operand->opcode() != HloOpcode::kConcatenate || operand->concatenate_dimension() != concat->concatenate_dimension()) { new_operands.push_back(operand); } else { changed = true; for (HloInstruction* operand_operand : operand->operands()) { new_operands.push_back(operand_operand); } } } if (changed) { auto new_concat = parent->AddInstruction(HloInstruction::CreateConcatenate( concat->shape(), new_operands, concat->concatenate_dimension())); TF_RETURN_IF_ERROR(parent->ReplaceInstruction(concat, new_concat)); } return changed; } absl::StatusOr<bool> SliceConcatForwarding(HloInstruction* slice) { if (slice->opcode() != HloOpcode::kSlice) { return false; } auto concat = slice->mutable_operand(0); if (concat->opcode() != HloOpcode::kConcatenate) { return false; } if (slice->shape().rank() != 1) { // Slice concat forwarding only work for size 1 tensor. return false; } int64_t concat_dim = concat->concatenate_dimension(); std::vector<HloInstruction*> new_operands; int64_t size_so_far = 0; int64_t slice_size = slice->shape().dimensions(concat_dim); if (slice_size != slice->slice_limits(0) - slice->slice_starts(0)) { return false; } if (slice->slice_strides(0) != 1) { return false; } for (HloInstruction* operand : concat->operands()) { if (size_so_far == slice->slice_starts(0) && operand->shape().dimensions(0) == slice_size) { // Found an operand that can be forwarded. TF_RETURN_IF_ERROR(slice->ReplaceAllUsesWith(operand)); return true; } size_so_far += operand->shape().dimensions(concat_dim); } return false; } absl::StatusOr<bool> ReshapeBroadcastForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto broadcast = reshape->mutable_operand(0); if (broadcast->opcode() != HloOpcode::kBroadcast) { return false; } if (reshape->shape().rank() != 0) { return false; } if (broadcast->shape().rank() != 1) { return false; } if (broadcast->mutable_operand(0)->shape().rank() != 0) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(broadcast->mutable_operand(0))); return true; } absl::StatusOr<bool> ReshapeReshapeForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto reshape_2 = reshape->mutable_operand(0); if (reshape_2->opcode() != HloOpcode::kReshape) { return false; } if (!Shape::Equal()(reshape->shape(), reshape_2->operand(0)->shape())) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(reshape_2->mutable_operand(0))); return true; } absl::StatusOr<bool> IdentityConvertRemoving(HloInstruction* convert) { if (convert->opcode() != HloOpcode::kConvert) { return false; } auto operand = convert->mutable_operand(0); if (Shape::Equal()(convert->shape(), operand->shape())) { TF_RETURN_IF_ERROR(convert->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> IdentityReshapeRemoving(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto operand = reshape->mutable_operand(0); if (Shape::Equal()(reshape->shape(), operand->shape())) { TF_RETURN_IF_ERROR(reshape->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> DynamicDimensionSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), before:\n" + module->ToString()); bool changed = false; for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, SliceConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeBroadcastForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeReshapeForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityConvertRemoving(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityReshapeRemoving(inst)); changed |= local_changed; } } XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), after:\n" + module->ToString()); return changed; } XLA_VLOG_LINES( XLA_VLOG_LINES(
#include "xla/service/dynamic_dimension_simplifier.h" #include <memory> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.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/layout_util.h" #include "xla/literal.h" #include "xla/service/hlo_creation_utils.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_fix.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/service/shape_inference.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" class DynamicDimensionSimplifierTest : public HloTestBase {}; TEST_F(DynamicDimensionSimplifierTest, DoNotForwardConcatSliceStrided) { const char* kModuleStr = R"( HloModule m test { p0 = s32[1] parameter(0) p1 = s32[1] parameter(1) p2 = s32[1] parameter(2) concat = s32[3] concatenate(p0, p1, p2), dimensions={0} ROOT slice = s32[1] slice(concat), slice={[1:2:2]} } )"; TF_ASSERT_OK_AND_ASSIGN(auto m, ParseAndReturnVerifiedModule(kModuleStr)); DynamicDimensionSimplifier simplifier; ASSERT_FALSE(simplifier.Run(m.get()).value()); }
DynamicDimensionSimplifierTest_ForwardConcat
xla/service/dynamic_dimension_simplifier_test.cc
absl::StatusOr<bool> ConcatForwarding(HloInstruction* concat) { if (concat->opcode() != HloOpcode::kConcatenate) { return false; } bool changed = false; auto parent = concat->parent(); std::vector<HloInstruction*> new_operands; for (HloInstruction* operand : concat->operands()) { if (operand->opcode() != HloOpcode::kConcatenate || operand->concatenate_dimension() != concat->concatenate_dimension()) { new_operands.push_back(operand); } else { changed = true; for (HloInstruction* operand_operand : operand->operands()) { new_operands.push_back(operand_operand); } } } if (changed) { auto new_concat = parent->AddInstruction(HloInstruction::CreateConcatenate( concat->shape(), new_operands, concat->concatenate_dimension())); TF_RETURN_IF_ERROR(parent->ReplaceInstruction(concat, new_concat)); } return changed; } absl::StatusOr<bool> SliceConcatForwarding(HloInstruction* slice) { if (slice->opcode() != HloOpcode::kSlice) { return false; } auto concat = slice->mutable_operand(0); if (concat->opcode() != HloOpcode::kConcatenate) { return false; } if (slice->shape().rank() != 1) { // Slice concat forwarding only work for size 1 tensor. return false; } int64_t concat_dim = concat->concatenate_dimension(); std::vector<HloInstruction*> new_operands; int64_t size_so_far = 0; int64_t slice_size = slice->shape().dimensions(concat_dim); if (slice_size != slice->slice_limits(0) - slice->slice_starts(0)) { return false; } if (slice->slice_strides(0) != 1) { return false; } for (HloInstruction* operand : concat->operands()) { if (size_so_far == slice->slice_starts(0) && operand->shape().dimensions(0) == slice_size) { // Found an operand that can be forwarded. TF_RETURN_IF_ERROR(slice->ReplaceAllUsesWith(operand)); return true; } size_so_far += operand->shape().dimensions(concat_dim); } return false; } absl::StatusOr<bool> ReshapeBroadcastForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto broadcast = reshape->mutable_operand(0); if (broadcast->opcode() != HloOpcode::kBroadcast) { return false; } if (reshape->shape().rank() != 0) { return false; } if (broadcast->shape().rank() != 1) { return false; } if (broadcast->mutable_operand(0)->shape().rank() != 0) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(broadcast->mutable_operand(0))); return true; } absl::StatusOr<bool> ReshapeReshapeForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto reshape_2 = reshape->mutable_operand(0); if (reshape_2->opcode() != HloOpcode::kReshape) { return false; } if (!Shape::Equal()(reshape->shape(), reshape_2->operand(0)->shape())) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(reshape_2->mutable_operand(0))); return true; } absl::StatusOr<bool> IdentityConvertRemoving(HloInstruction* convert) { if (convert->opcode() != HloOpcode::kConvert) { return false; } auto operand = convert->mutable_operand(0); if (Shape::Equal()(convert->shape(), operand->shape())) { TF_RETURN_IF_ERROR(convert->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> IdentityReshapeRemoving(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto operand = reshape->mutable_operand(0); if (Shape::Equal()(reshape->shape(), operand->shape())) { TF_RETURN_IF_ERROR(reshape->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> DynamicDimensionSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), before:\n" + module->ToString()); bool changed = false; for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, SliceConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeBroadcastForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeReshapeForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityConvertRemoving(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityReshapeRemoving(inst)); changed |= local_changed; } } XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), after:\n" + module->ToString()); return changed; } XLA_VLOG_LINES( XLA_VLOG_LINES(
#include "xla/service/dynamic_dimension_simplifier.h" #include <memory> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.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/layout_util.h" #include "xla/literal.h" #include "xla/service/hlo_creation_utils.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_fix.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/service/shape_inference.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" class DynamicDimensionSimplifierTest : public HloTestBase {}; TEST_F(DynamicDimensionSimplifierTest, ForwardConcat) { const char* kModuleStr = R"( HloModule m test { p0 = s32[1] parameter(0) p1 = s32[1] parameter(1) p2 = s32[1] parameter(2) concat1 = s32[2] concatenate(p0, p1), dimensions={0} ROOT concat2 = s32[3] concatenate(concat1, p2), dimensions={0} } )"; TF_ASSERT_OK_AND_ASSIGN(auto m, ParseAndReturnVerifiedModule(kModuleStr)); DynamicDimensionSimplifier simplifier; ASSERT_TRUE(simplifier.Run(m.get()).value()); EXPECT_THAT(m->entry_computation()->root_instruction(), GmockMatch(m::Concatenate(m::Parameter(0), m::Parameter(1), m::Parameter(2)))); }
DynamicDimensionSimplifierTest_ForwardConcatSlice
xla/service/dynamic_dimension_simplifier_test.cc
absl::StatusOr<bool> ConcatForwarding(HloInstruction* concat) { if (concat->opcode() != HloOpcode::kConcatenate) { return false; } bool changed = false; auto parent = concat->parent(); std::vector<HloInstruction*> new_operands; for (HloInstruction* operand : concat->operands()) { if (operand->opcode() != HloOpcode::kConcatenate || operand->concatenate_dimension() != concat->concatenate_dimension()) { new_operands.push_back(operand); } else { changed = true; for (HloInstruction* operand_operand : operand->operands()) { new_operands.push_back(operand_operand); } } } if (changed) { auto new_concat = parent->AddInstruction(HloInstruction::CreateConcatenate( concat->shape(), new_operands, concat->concatenate_dimension())); TF_RETURN_IF_ERROR(parent->ReplaceInstruction(concat, new_concat)); } return changed; } absl::StatusOr<bool> SliceConcatForwarding(HloInstruction* slice) { if (slice->opcode() != HloOpcode::kSlice) { return false; } auto concat = slice->mutable_operand(0); if (concat->opcode() != HloOpcode::kConcatenate) { return false; } if (slice->shape().rank() != 1) { // Slice concat forwarding only work for size 1 tensor. return false; } int64_t concat_dim = concat->concatenate_dimension(); std::vector<HloInstruction*> new_operands; int64_t size_so_far = 0; int64_t slice_size = slice->shape().dimensions(concat_dim); if (slice_size != slice->slice_limits(0) - slice->slice_starts(0)) { return false; } if (slice->slice_strides(0) != 1) { return false; } for (HloInstruction* operand : concat->operands()) { if (size_so_far == slice->slice_starts(0) && operand->shape().dimensions(0) == slice_size) { // Found an operand that can be forwarded. TF_RETURN_IF_ERROR(slice->ReplaceAllUsesWith(operand)); return true; } size_so_far += operand->shape().dimensions(concat_dim); } return false; } absl::StatusOr<bool> ReshapeBroadcastForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto broadcast = reshape->mutable_operand(0); if (broadcast->opcode() != HloOpcode::kBroadcast) { return false; } if (reshape->shape().rank() != 0) { return false; } if (broadcast->shape().rank() != 1) { return false; } if (broadcast->mutable_operand(0)->shape().rank() != 0) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(broadcast->mutable_operand(0))); return true; } absl::StatusOr<bool> ReshapeReshapeForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto reshape_2 = reshape->mutable_operand(0); if (reshape_2->opcode() != HloOpcode::kReshape) { return false; } if (!Shape::Equal()(reshape->shape(), reshape_2->operand(0)->shape())) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(reshape_2->mutable_operand(0))); return true; } absl::StatusOr<bool> IdentityConvertRemoving(HloInstruction* convert) { if (convert->opcode() != HloOpcode::kConvert) { return false; } auto operand = convert->mutable_operand(0); if (Shape::Equal()(convert->shape(), operand->shape())) { TF_RETURN_IF_ERROR(convert->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> IdentityReshapeRemoving(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto operand = reshape->mutable_operand(0); if (Shape::Equal()(reshape->shape(), operand->shape())) { TF_RETURN_IF_ERROR(reshape->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> DynamicDimensionSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), before:\n" + module->ToString()); bool changed = false; for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, SliceConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeBroadcastForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeReshapeForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityConvertRemoving(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityReshapeRemoving(inst)); changed |= local_changed; } } XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), after:\n" + module->ToString()); return changed; } XLA_VLOG_LINES( XLA_VLOG_LINES(
#include "xla/service/dynamic_dimension_simplifier.h" #include <memory> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.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/layout_util.h" #include "xla/literal.h" #include "xla/service/hlo_creation_utils.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_fix.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/service/shape_inference.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" class DynamicDimensionSimplifierTest : public HloTestBase {}; TEST_F(DynamicDimensionSimplifierTest, ForwardConcatSlice) { const char* kModuleStr = R"( HloModule m test { p0 = s32[1] parameter(0) p1 = s32[1] parameter(1) p2 = s32[1] parameter(2) concat = s32[3] concatenate(p0, p1, p2), dimensions={0} ROOT slice = s32[1] slice(concat), slice={[1:2]} } )"; TF_ASSERT_OK_AND_ASSIGN(auto m, ParseAndReturnVerifiedModule(kModuleStr)); DynamicDimensionSimplifier simplifier; ASSERT_TRUE(simplifier.Run(m.get()).value()); EXPECT_THAT(m->entry_computation()->root_instruction(), GmockMatch(m::Parameter(1))); }
DynamicDimensionSimplifierTest_IdConvertRemoving
xla/service/dynamic_dimension_simplifier_test.cc
absl::StatusOr<bool> ConcatForwarding(HloInstruction* concat) { if (concat->opcode() != HloOpcode::kConcatenate) { return false; } bool changed = false; auto parent = concat->parent(); std::vector<HloInstruction*> new_operands; for (HloInstruction* operand : concat->operands()) { if (operand->opcode() != HloOpcode::kConcatenate || operand->concatenate_dimension() != concat->concatenate_dimension()) { new_operands.push_back(operand); } else { changed = true; for (HloInstruction* operand_operand : operand->operands()) { new_operands.push_back(operand_operand); } } } if (changed) { auto new_concat = parent->AddInstruction(HloInstruction::CreateConcatenate( concat->shape(), new_operands, concat->concatenate_dimension())); TF_RETURN_IF_ERROR(parent->ReplaceInstruction(concat, new_concat)); } return changed; } absl::StatusOr<bool> SliceConcatForwarding(HloInstruction* slice) { if (slice->opcode() != HloOpcode::kSlice) { return false; } auto concat = slice->mutable_operand(0); if (concat->opcode() != HloOpcode::kConcatenate) { return false; } if (slice->shape().rank() != 1) { // Slice concat forwarding only work for size 1 tensor. return false; } int64_t concat_dim = concat->concatenate_dimension(); std::vector<HloInstruction*> new_operands; int64_t size_so_far = 0; int64_t slice_size = slice->shape().dimensions(concat_dim); if (slice_size != slice->slice_limits(0) - slice->slice_starts(0)) { return false; } if (slice->slice_strides(0) != 1) { return false; } for (HloInstruction* operand : concat->operands()) { if (size_so_far == slice->slice_starts(0) && operand->shape().dimensions(0) == slice_size) { // Found an operand that can be forwarded. TF_RETURN_IF_ERROR(slice->ReplaceAllUsesWith(operand)); return true; } size_so_far += operand->shape().dimensions(concat_dim); } return false; } absl::StatusOr<bool> ReshapeBroadcastForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto broadcast = reshape->mutable_operand(0); if (broadcast->opcode() != HloOpcode::kBroadcast) { return false; } if (reshape->shape().rank() != 0) { return false; } if (broadcast->shape().rank() != 1) { return false; } if (broadcast->mutable_operand(0)->shape().rank() != 0) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(broadcast->mutable_operand(0))); return true; } absl::StatusOr<bool> ReshapeReshapeForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto reshape_2 = reshape->mutable_operand(0); if (reshape_2->opcode() != HloOpcode::kReshape) { return false; } if (!Shape::Equal()(reshape->shape(), reshape_2->operand(0)->shape())) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(reshape_2->mutable_operand(0))); return true; } absl::StatusOr<bool> IdentityConvertRemoving(HloInstruction* convert) { if (convert->opcode() != HloOpcode::kConvert) { return false; } auto operand = convert->mutable_operand(0); if (Shape::Equal()(convert->shape(), operand->shape())) { TF_RETURN_IF_ERROR(convert->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> IdentityReshapeRemoving(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto operand = reshape->mutable_operand(0); if (Shape::Equal()(reshape->shape(), operand->shape())) { TF_RETURN_IF_ERROR(reshape->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> DynamicDimensionSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), before:\n" + module->ToString()); bool changed = false; for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, SliceConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeBroadcastForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeReshapeForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityConvertRemoving(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityReshapeRemoving(inst)); changed |= local_changed; } } XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), after:\n" + module->ToString()); return changed; } XLA_VLOG_LINES( XLA_VLOG_LINES(
#include "xla/service/dynamic_dimension_simplifier.h" #include <memory> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.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/layout_util.h" #include "xla/literal.h" #include "xla/service/hlo_creation_utils.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_fix.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/service/shape_inference.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" class DynamicDimensionSimplifierTest : public HloTestBase {}; TEST_F(DynamicDimensionSimplifierTest, IdConvertRemoving) { const char* kModuleStr = R"( HloModule m test { p0 = s32[1] parameter(0) ROOT reshape2 = s32[1] convert(p0) } )"; TF_ASSERT_OK_AND_ASSIGN(auto m, ParseAndReturnVerifiedModule(kModuleStr)); DynamicDimensionSimplifier simplifier; ASSERT_TRUE(simplifier.Run(m.get()).value()); EXPECT_THAT(m->entry_computation()->root_instruction(), GmockMatch(m::Parameter(0))); }
DynamicDimensionSimplifierTest_ReshapeReshapeForwarding
xla/service/dynamic_dimension_simplifier_test.cc
absl::StatusOr<bool> ConcatForwarding(HloInstruction* concat) { if (concat->opcode() != HloOpcode::kConcatenate) { return false; } bool changed = false; auto parent = concat->parent(); std::vector<HloInstruction*> new_operands; for (HloInstruction* operand : concat->operands()) { if (operand->opcode() != HloOpcode::kConcatenate || operand->concatenate_dimension() != concat->concatenate_dimension()) { new_operands.push_back(operand); } else { changed = true; for (HloInstruction* operand_operand : operand->operands()) { new_operands.push_back(operand_operand); } } } if (changed) { auto new_concat = parent->AddInstruction(HloInstruction::CreateConcatenate( concat->shape(), new_operands, concat->concatenate_dimension())); TF_RETURN_IF_ERROR(parent->ReplaceInstruction(concat, new_concat)); } return changed; } absl::StatusOr<bool> SliceConcatForwarding(HloInstruction* slice) { if (slice->opcode() != HloOpcode::kSlice) { return false; } auto concat = slice->mutable_operand(0); if (concat->opcode() != HloOpcode::kConcatenate) { return false; } if (slice->shape().rank() != 1) { // Slice concat forwarding only work for size 1 tensor. return false; } int64_t concat_dim = concat->concatenate_dimension(); std::vector<HloInstruction*> new_operands; int64_t size_so_far = 0; int64_t slice_size = slice->shape().dimensions(concat_dim); if (slice_size != slice->slice_limits(0) - slice->slice_starts(0)) { return false; } if (slice->slice_strides(0) != 1) { return false; } for (HloInstruction* operand : concat->operands()) { if (size_so_far == slice->slice_starts(0) && operand->shape().dimensions(0) == slice_size) { // Found an operand that can be forwarded. TF_RETURN_IF_ERROR(slice->ReplaceAllUsesWith(operand)); return true; } size_so_far += operand->shape().dimensions(concat_dim); } return false; } absl::StatusOr<bool> ReshapeBroadcastForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto broadcast = reshape->mutable_operand(0); if (broadcast->opcode() != HloOpcode::kBroadcast) { return false; } if (reshape->shape().rank() != 0) { return false; } if (broadcast->shape().rank() != 1) { return false; } if (broadcast->mutable_operand(0)->shape().rank() != 0) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(broadcast->mutable_operand(0))); return true; } absl::StatusOr<bool> ReshapeReshapeForwarding(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto reshape_2 = reshape->mutable_operand(0); if (reshape_2->opcode() != HloOpcode::kReshape) { return false; } if (!Shape::Equal()(reshape->shape(), reshape_2->operand(0)->shape())) { return false; } TF_RETURN_IF_ERROR( reshape->ReplaceAllUsesWith(reshape_2->mutable_operand(0))); return true; } absl::StatusOr<bool> IdentityConvertRemoving(HloInstruction* convert) { if (convert->opcode() != HloOpcode::kConvert) { return false; } auto operand = convert->mutable_operand(0); if (Shape::Equal()(convert->shape(), operand->shape())) { TF_RETURN_IF_ERROR(convert->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> IdentityReshapeRemoving(HloInstruction* reshape) { if (reshape->opcode() != HloOpcode::kReshape) { return false; } auto operand = reshape->mutable_operand(0); if (Shape::Equal()(reshape->shape(), operand->shape())) { TF_RETURN_IF_ERROR(reshape->ReplaceAllUsesWith(operand)); return true; } return false; } absl::StatusOr<bool> DynamicDimensionSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), before:\n" + module->ToString()); bool changed = false; for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, SliceConcatForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeBroadcastForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, ReshapeReshapeForwarding(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityConvertRemoving(inst)); changed |= local_changed; } } for (auto* comp : module->MakeNonfusionComputations(execution_threads)) { for (auto* inst : comp->MakeInstructionPostOrder()) { TF_ASSIGN_OR_RETURN(bool local_changed, IdentityReshapeRemoving(inst)); changed |= local_changed; } } XLA_VLOG_LINES( 2, "DynamicDimensionSimplifier::Run(), after:\n" + module->ToString()); return changed; } XLA_VLOG_LINES( XLA_VLOG_LINES(
#include "xla/service/dynamic_dimension_simplifier.h" #include <memory> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.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/layout_util.h" #include "xla/literal.h" #include "xla/service/hlo_creation_utils.h" #include "xla/service/hlo_parser.h" #include "xla/service/hlo_pass_fix.h" #include "xla/service/hlo_pass_pipeline.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/service/shape_inference.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" class DynamicDimensionSimplifierTest : public HloTestBase {}; TEST_F(DynamicDimensionSimplifierTest, ReshapeReshapeForwarding) { const char* kModuleStr = R"( HloModule m test { p0 = s32[] parameter(0) reshape = s32[1] reshape(p0) ROOT reshape2 = s32[] reshape(reshape) } )"; TF_ASSERT_OK_AND_ASSIGN(auto m, ParseAndReturnVerifiedModule(kModuleStr)); DynamicDimensionSimplifier simplifier; ASSERT_TRUE(simplifier.Run(m.get()).value()); EXPECT_THAT(m->entry_computation()->root_instruction(), GmockMatch(m::Parameter(0))); }
FlattenCallGraphTest_ComplexGraph
xla/service/flatten_call_graph_test.cc
void ReplaceCalledComputation(HloInstruction* instruction, HloComputation* computation, HloComputation* new_computation) { switch (instruction->opcode()) { case HloOpcode::kWhile: { if (computation == instruction->while_condition()) { instruction->set_while_condition(new_computation); } else { CHECK_EQ(computation, instruction->while_body()); instruction->set_while_body(new_computation); } break; } case HloOpcode::kCall: { CHECK_EQ(instruction->to_apply(), computation); instruction->set_to_apply(new_computation); break; } case HloOpcode::kConditional: { for (int b = 0; b < instruction->branch_count(); ++b) { if (b == instruction->branch_count() - 1) { CHECK_EQ(computation, instruction->branch_computation(b)); } if (computation == instruction->branch_computation(b)) { instruction->set_branch_computation(b, new_computation); break; } } break; } default: LOG(FATAL) << "unexpected opcode: " << instruction->opcode(); } } absl::Status FlattenNode(const CallGraphNode& node) { HloComputation* computation = node.computation(); HloModule* module = computation->parent(); // Clone callee for all call-sites except the first one. for (int i = 0; i < node.caller_callsites().size(); ++i) { CallSite call_site = node.caller_callsites()[i]; // Only consider sequential call contexts. if (call_site.context() == CallContext::kEmbedded) { continue; } CHECK_EQ(call_site.context(), CallContext::kControlFlow); // Skip first element if this computation is only called from a sequential // context. if (node.context() != CallContext::kBoth && i == 0) { continue; } if (computation->IsAsyncComputation()) { continue; } // Clone computation for the remaining sequential context call sites. HloComputation* clone = module->AddEmbeddedComputation(computation->Clone()); ReplaceCalledComputation(call_site.instruction(), computation, clone); // Clone the sub-tree of all computations called from this node. std::vector<HloComputation*> worklist; worklist.push_back(clone); while (!worklist.empty()) { auto current = worklist.back(); worklist.pop_back(); for (auto* instruction : current->instructions()) { if (GetInstructionCallContext(instruction->opcode()) != CallContext::kControlFlow) { continue; } for (auto callee : instruction->called_computations()) { HloComputation* callee_clone = module->AddEmbeddedComputation(callee->Clone()); ReplaceCalledComputation(instruction, callee, callee_clone); worklist.push_back(callee_clone); } } } } return absl::OkStatus(); } absl::Status AnnotateNode(const CallGraphNode& node) { for (auto& callsite : node.callsites()) { HloInstruction* instruction = callsite.instruction(); if (instruction->opcode() == HloOpcode::kFusion) { for (HloComputation* computation : instruction->called_computations()) { computation->SetFusionInstruction(instruction); } } else if (instruction->opcode() == HloOpcode::kCustomCall) { for (HloComputation* computation : instruction->called_computations()) { computation->SetCustomCallInstruction(instruction); } } else if (hlo_query::IsCollectiveCommunicationOp(instruction->opcode())) { for (HloComputation* computation : instruction->called_computations()) { computation->SetCollectiveCallInstruction(instruction); } } else if (instruction->opcode() == HloOpcode::kWhile) { instruction->while_body()->SetWhileCallInstruction(instruction); } else if (instruction->opcode() == HloOpcode::kConditional) { for (HloComputation* branch : instruction->branch_computations()) { branch->SetConditionalCallInstruction(instruction); } } } return absl::OkStatus(); } absl::StatusOr<bool> FlattenCallGraph::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { XLA_VLOG_LINES(3, "Before flatten call graph:\n" + module->ToString()); { // Flatten original call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module, execution_threads); TF_RETURN_IF_ERROR(call_graph->VisitNodes(FlattenNode)); } { // Annotate flattened computations with callee types. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module, execution_threads); TF_RETURN_IF_ERROR(call_graph->VisitNodes(AnnotateNode)); } XLA_VLOG_LINES(3, "After flatten call graph:\n" + module->ToString()); return true; } XLA_VLOG_LINES(3, "Before flatten call graph:\n" + module->ToString()); XLA_VLOG_LINES(3, "After flatten call graph:\n" + module->ToString());
#include "xla/service/flatten_call_graph.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/literal.h" #include "xla/service/call_graph.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" class FlattenCallGraphTest : public HloTestBase { protected: // Build and return a trivial computation taking and returning a scalar. std::unique_ptr<HloComputation> MakeScalarComputation() { HloComputation::Builder builder(TestName() + ".ScalarComputation"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); builder.AddInstruction( HloInstruction::CreateUnary(kScalarShape, HloOpcode::kNegate, param0)); return builder.Build(); } // Build and return a computation which takes a scalar and maps (kMap) the // given computation to the value 'callsites' number of times. std::unique_ptr<HloComputation> MakeMappingComputation( HloComputation* map_computation, int64_t callsites) { HloComputation::Builder builder(TestName() + ".MappingComputation"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* last_value = param0; for (int64_t i = 0; i < callsites; ++i) { last_value = builder.AddInstruction(HloInstruction::CreateMap( kScalarShape, {last_value}, map_computation)); } return builder.Build(); } // Build and return a computation which takes a scalar and calls (kCall) the // given computation with value 'callsites' number of times. std::unique_ptr<HloComputation> MakeCallingComputation( HloComputation* callee_computation, int64_t callsites, const std::string& suffix = ".CallingComputation") { HloComputation::Builder builder(TestName() + suffix); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* last_value = param0; for (int64_t i = 0; i < callsites; ++i) { last_value = builder.AddInstruction(HloInstruction::CreateCall( kScalarShape, {last_value}, callee_computation)); } return builder.Build(); } // Build and return a computation which takes a scalar and returns a PRED // value. std::unique_ptr<HloComputation> MakeConditionComputation() { HloComputation::Builder builder(TestName() + ".ConditionComputation"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* zero = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(0.0f))); builder.AddInstruction( HloInstruction::CreateCompare(ShapeUtil::MakeShape(PRED, {}), param0, zero, ComparisonDirection::kGt)); return builder.Build(); } absl::StatusOr<bool> RunFlattenCallGraph(HloModule* module) { FlattenCallGraph flatten; TF_ASSIGN_OR_RETURN(bool result, flatten.Run(module)); return result; } const Shape kScalarShape = ShapeUtil::MakeShape(F32, {}); }; TEST_F(FlattenCallGraphTest, ComplexGraph) { // Test a call graph of a module with several computation called in various // contexts. The call graph looks like: // // entry // / | // a | // / | \ | // b | cond // \ | // c // // Calls are made via kCall, kWhile, and kMap instructions. auto module = CreateNewVerifiedModule(); HloComputation* cond_computation = module->AddEmbeddedComputation(MakeConditionComputation()); HloComputation* c_computation = module->AddEmbeddedComputation(MakeScalarComputation()); HloComputation* b_computation = module->AddEmbeddedComputation( MakeMappingComputation(c_computation, /*callsites=*/1)); HloComputation* a_computation; { HloComputation::Builder builder(TestName() + ".a"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* call = builder.AddInstruction( HloInstruction::CreateCall(kScalarShape, {param0}, c_computation)); builder.AddInstruction(HloInstruction::CreateWhile( kScalarShape, cond_computation, b_computation, call)); a_computation = module->AddEmbeddedComputation(builder.Build()); } HloComputation* entry_computation; { HloComputation::Builder builder(TestName() + ".entry"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); builder.AddInstruction(HloInstruction::CreateWhile( kScalarShape, cond_computation, a_computation, param0)); entry_computation = module->AddEntryComputation(builder.Build()); } { TF_ASSERT_OK_AND_ASSIGN(bool result, RunFlattenCallGraph(module.get())); EXPECT_TRUE(result); std::unique_ptr<CallGraph> flat_call_graph = CallGraph::Build(module.get()); const CallGraphNode& c_node = flat_call_graph->GetNode(c_computation); EXPECT_EQ(1, c_node.caller_callsites().size()); } }
FlattenCallGraphTest_FlattenCalls
xla/service/flatten_call_graph_test.cc
void ReplaceCalledComputation(HloInstruction* instruction, HloComputation* computation, HloComputation* new_computation) { switch (instruction->opcode()) { case HloOpcode::kWhile: { if (computation == instruction->while_condition()) { instruction->set_while_condition(new_computation); } else { CHECK_EQ(computation, instruction->while_body()); instruction->set_while_body(new_computation); } break; } case HloOpcode::kCall: { CHECK_EQ(instruction->to_apply(), computation); instruction->set_to_apply(new_computation); break; } case HloOpcode::kConditional: { for (int b = 0; b < instruction->branch_count(); ++b) { if (b == instruction->branch_count() - 1) { CHECK_EQ(computation, instruction->branch_computation(b)); } if (computation == instruction->branch_computation(b)) { instruction->set_branch_computation(b, new_computation); break; } } break; } default: LOG(FATAL) << "unexpected opcode: " << instruction->opcode(); } } absl::Status FlattenNode(const CallGraphNode& node) { HloComputation* computation = node.computation(); HloModule* module = computation->parent(); // Clone callee for all call-sites except the first one. for (int i = 0; i < node.caller_callsites().size(); ++i) { CallSite call_site = node.caller_callsites()[i]; // Only consider sequential call contexts. if (call_site.context() == CallContext::kEmbedded) { continue; } CHECK_EQ(call_site.context(), CallContext::kControlFlow); // Skip first element if this computation is only called from a sequential // context. if (node.context() != CallContext::kBoth && i == 0) { continue; } if (computation->IsAsyncComputation()) { continue; } // Clone computation for the remaining sequential context call sites. HloComputation* clone = module->AddEmbeddedComputation(computation->Clone()); ReplaceCalledComputation(call_site.instruction(), computation, clone); // Clone the sub-tree of all computations called from this node. std::vector<HloComputation*> worklist; worklist.push_back(clone); while (!worklist.empty()) { auto current = worklist.back(); worklist.pop_back(); for (auto* instruction : current->instructions()) { if (GetInstructionCallContext(instruction->opcode()) != CallContext::kControlFlow) { continue; } for (auto callee : instruction->called_computations()) { HloComputation* callee_clone = module->AddEmbeddedComputation(callee->Clone()); ReplaceCalledComputation(instruction, callee, callee_clone); worklist.push_back(callee_clone); } } } } return absl::OkStatus(); } absl::Status AnnotateNode(const CallGraphNode& node) { for (auto& callsite : node.callsites()) { HloInstruction* instruction = callsite.instruction(); if (instruction->opcode() == HloOpcode::kFusion) { for (HloComputation* computation : instruction->called_computations()) { computation->SetFusionInstruction(instruction); } } else if (instruction->opcode() == HloOpcode::kCustomCall) { for (HloComputation* computation : instruction->called_computations()) { computation->SetCustomCallInstruction(instruction); } } else if (hlo_query::IsCollectiveCommunicationOp(instruction->opcode())) { for (HloComputation* computation : instruction->called_computations()) { computation->SetCollectiveCallInstruction(instruction); } } else if (instruction->opcode() == HloOpcode::kWhile) { instruction->while_body()->SetWhileCallInstruction(instruction); } else if (instruction->opcode() == HloOpcode::kConditional) { for (HloComputation* branch : instruction->branch_computations()) { branch->SetConditionalCallInstruction(instruction); } } } return absl::OkStatus(); } absl::StatusOr<bool> FlattenCallGraph::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { XLA_VLOG_LINES(3, "Before flatten call graph:\n" + module->ToString()); { // Flatten original call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module, execution_threads); TF_RETURN_IF_ERROR(call_graph->VisitNodes(FlattenNode)); } { // Annotate flattened computations with callee types. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module, execution_threads); TF_RETURN_IF_ERROR(call_graph->VisitNodes(AnnotateNode)); } XLA_VLOG_LINES(3, "After flatten call graph:\n" + module->ToString()); return true; } XLA_VLOG_LINES(3, "Before flatten call graph:\n" + module->ToString()); XLA_VLOG_LINES(3, "After flatten call graph:\n" + module->ToString());
#include "xla/service/flatten_call_graph.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/literal.h" #include "xla/service/call_graph.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" class FlattenCallGraphTest : public HloTestBase { protected: // Build and return a trivial computation taking and returning a scalar. std::unique_ptr<HloComputation> MakeScalarComputation() { HloComputation::Builder builder(TestName() + ".ScalarComputation"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); builder.AddInstruction( HloInstruction::CreateUnary(kScalarShape, HloOpcode::kNegate, param0)); return builder.Build(); } // Build and return a computation which takes a scalar and maps (kMap) the // given computation to the value 'callsites' number of times. std::unique_ptr<HloComputation> MakeMappingComputation( HloComputation* map_computation, int64_t callsites) { HloComputation::Builder builder(TestName() + ".MappingComputation"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* last_value = param0; for (int64_t i = 0; i < callsites; ++i) { last_value = builder.AddInstruction(HloInstruction::CreateMap( kScalarShape, {last_value}, map_computation)); } return builder.Build(); } // Build and return a computation which takes a scalar and calls (kCall) the // given computation with value 'callsites' number of times. std::unique_ptr<HloComputation> MakeCallingComputation( HloComputation* callee_computation, int64_t callsites, const std::string& suffix = ".CallingComputation") { HloComputation::Builder builder(TestName() + suffix); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* last_value = param0; for (int64_t i = 0; i < callsites; ++i) { last_value = builder.AddInstruction(HloInstruction::CreateCall( kScalarShape, {last_value}, callee_computation)); } return builder.Build(); } // Build and return a computation which takes a scalar and returns a PRED // value. std::unique_ptr<HloComputation> MakeConditionComputation() { HloComputation::Builder builder(TestName() + ".ConditionComputation"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* zero = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(0.0f))); builder.AddInstruction( HloInstruction::CreateCompare(ShapeUtil::MakeShape(PRED, {}), param0, zero, ComparisonDirection::kGt)); return builder.Build(); } absl::StatusOr<bool> RunFlattenCallGraph(HloModule* module) { FlattenCallGraph flatten; TF_ASSIGN_OR_RETURN(bool result, flatten.Run(module)); return result; } const Shape kScalarShape = ShapeUtil::MakeShape(F32, {}); }; TEST_F(FlattenCallGraphTest, FlattenCalls) { auto module = CreateNewVerifiedModule(); HloComputation* c_computation = module->AddEmbeddedComputation(MakeScalarComputation()); HloComputation* b_computation = module->AddEmbeddedComputation( MakeCallingComputation(c_computation, /*callsites=*/2, ".B")); module->AddEntryComputation( MakeCallingComputation(b_computation, /*callsites=*/2, ".Entry")); TF_ASSERT_OK_AND_ASSIGN(bool result, RunFlattenCallGraph(module.get())); EXPECT_TRUE(result); std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module.get()); EXPECT_EQ(7, module->computation_count()); const CallGraphNode& c_node = call_graph->GetNode(c_computation); EXPECT_EQ(1, c_node.caller_callsites().size()); const CallGraphNode& b_node = call_graph->GetNode(b_computation); EXPECT_EQ(1, b_node.caller_callsites().size()); }
FlattenCallGraphTest_SharedWhileConditionAndBody
xla/service/flatten_call_graph_test.cc
void ReplaceCalledComputation(HloInstruction* instruction, HloComputation* computation, HloComputation* new_computation) { switch (instruction->opcode()) { case HloOpcode::kWhile: { if (computation == instruction->while_condition()) { instruction->set_while_condition(new_computation); } else { CHECK_EQ(computation, instruction->while_body()); instruction->set_while_body(new_computation); } break; } case HloOpcode::kCall: { CHECK_EQ(instruction->to_apply(), computation); instruction->set_to_apply(new_computation); break; } case HloOpcode::kConditional: { for (int b = 0; b < instruction->branch_count(); ++b) { if (b == instruction->branch_count() - 1) { CHECK_EQ(computation, instruction->branch_computation(b)); } if (computation == instruction->branch_computation(b)) { instruction->set_branch_computation(b, new_computation); break; } } break; } default: LOG(FATAL) << "unexpected opcode: " << instruction->opcode(); } } absl::Status FlattenNode(const CallGraphNode& node) { HloComputation* computation = node.computation(); HloModule* module = computation->parent(); // Clone callee for all call-sites except the first one. for (int i = 0; i < node.caller_callsites().size(); ++i) { CallSite call_site = node.caller_callsites()[i]; // Only consider sequential call contexts. if (call_site.context() == CallContext::kEmbedded) { continue; } CHECK_EQ(call_site.context(), CallContext::kControlFlow); // Skip first element if this computation is only called from a sequential // context. if (node.context() != CallContext::kBoth && i == 0) { continue; } if (computation->IsAsyncComputation()) { continue; } // Clone computation for the remaining sequential context call sites. HloComputation* clone = module->AddEmbeddedComputation(computation->Clone()); ReplaceCalledComputation(call_site.instruction(), computation, clone); // Clone the sub-tree of all computations called from this node. std::vector<HloComputation*> worklist; worklist.push_back(clone); while (!worklist.empty()) { auto current = worklist.back(); worklist.pop_back(); for (auto* instruction : current->instructions()) { if (GetInstructionCallContext(instruction->opcode()) != CallContext::kControlFlow) { continue; } for (auto callee : instruction->called_computations()) { HloComputation* callee_clone = module->AddEmbeddedComputation(callee->Clone()); ReplaceCalledComputation(instruction, callee, callee_clone); worklist.push_back(callee_clone); } } } } return absl::OkStatus(); } absl::Status AnnotateNode(const CallGraphNode& node) { for (auto& callsite : node.callsites()) { HloInstruction* instruction = callsite.instruction(); if (instruction->opcode() == HloOpcode::kFusion) { for (HloComputation* computation : instruction->called_computations()) { computation->SetFusionInstruction(instruction); } } else if (instruction->opcode() == HloOpcode::kCustomCall) { for (HloComputation* computation : instruction->called_computations()) { computation->SetCustomCallInstruction(instruction); } } else if (hlo_query::IsCollectiveCommunicationOp(instruction->opcode())) { for (HloComputation* computation : instruction->called_computations()) { computation->SetCollectiveCallInstruction(instruction); } } else if (instruction->opcode() == HloOpcode::kWhile) { instruction->while_body()->SetWhileCallInstruction(instruction); } else if (instruction->opcode() == HloOpcode::kConditional) { for (HloComputation* branch : instruction->branch_computations()) { branch->SetConditionalCallInstruction(instruction); } } } return absl::OkStatus(); } absl::StatusOr<bool> FlattenCallGraph::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { XLA_VLOG_LINES(3, "Before flatten call graph:\n" + module->ToString()); { // Flatten original call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module, execution_threads); TF_RETURN_IF_ERROR(call_graph->VisitNodes(FlattenNode)); } { // Annotate flattened computations with callee types. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module, execution_threads); TF_RETURN_IF_ERROR(call_graph->VisitNodes(AnnotateNode)); } XLA_VLOG_LINES(3, "After flatten call graph:\n" + module->ToString()); return true; } XLA_VLOG_LINES(3, "Before flatten call graph:\n" + module->ToString()); XLA_VLOG_LINES(3, "After flatten call graph:\n" + module->ToString());
#include "xla/service/flatten_call_graph.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/literal.h" #include "xla/service/call_graph.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" class FlattenCallGraphTest : public HloTestBase { protected: // Build and return a trivial computation taking and returning a scalar. std::unique_ptr<HloComputation> MakeScalarComputation() { HloComputation::Builder builder(TestName() + ".ScalarComputation"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); builder.AddInstruction( HloInstruction::CreateUnary(kScalarShape, HloOpcode::kNegate, param0)); return builder.Build(); } // Build and return a computation which takes a scalar and maps (kMap) the // given computation to the value 'callsites' number of times. std::unique_ptr<HloComputation> MakeMappingComputation( HloComputation* map_computation, int64_t callsites) { HloComputation::Builder builder(TestName() + ".MappingComputation"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* last_value = param0; for (int64_t i = 0; i < callsites; ++i) { last_value = builder.AddInstruction(HloInstruction::CreateMap( kScalarShape, {last_value}, map_computation)); } return builder.Build(); } // Build and return a computation which takes a scalar and calls (kCall) the // given computation with value 'callsites' number of times. std::unique_ptr<HloComputation> MakeCallingComputation( HloComputation* callee_computation, int64_t callsites, const std::string& suffix = ".CallingComputation") { HloComputation::Builder builder(TestName() + suffix); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* last_value = param0; for (int64_t i = 0; i < callsites; ++i) { last_value = builder.AddInstruction(HloInstruction::CreateCall( kScalarShape, {last_value}, callee_computation)); } return builder.Build(); } // Build and return a computation which takes a scalar and returns a PRED // value. std::unique_ptr<HloComputation> MakeConditionComputation() { HloComputation::Builder builder(TestName() + ".ConditionComputation"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* zero = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(0.0f))); builder.AddInstruction( HloInstruction::CreateCompare(ShapeUtil::MakeShape(PRED, {}), param0, zero, ComparisonDirection::kGt)); return builder.Build(); } absl::StatusOr<bool> RunFlattenCallGraph(HloModule* module) { FlattenCallGraph flatten; TF_ASSIGN_OR_RETURN(bool result, flatten.Run(module)); return result; } const Shape kScalarShape = ShapeUtil::MakeShape(F32, {}); }; TEST_F(FlattenCallGraphTest, SharedWhileConditionAndBody) { auto module = CreateNewVerifiedModule(); HloComputation* cond_computation; { HloComputation::Builder builder(TestName() + ".cond"); HloInstruction* param0 = builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeShape(PRED, {}), "param0")); HloInstruction* false_constant = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<bool>(false))); builder.AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), param0, false_constant, ComparisonDirection::kEq)); cond_computation = module->AddEmbeddedComputation(builder.Build()); } HloComputation* entry_computation; { HloComputation::Builder builder(TestName() + ".entry"); HloInstruction* false_constant = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<bool>(false))); builder.AddInstruction(HloInstruction::CreateWhile( ShapeUtil::MakeShape(PRED, {}), cond_computation, cond_computation, false_constant)); entry_computation = module->AddEntryComputation(builder.Build()); } { std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module.get()); const CallGraphNode& cond_node = call_graph->GetNode(cond_computation); EXPECT_EQ(2, cond_node.caller_callsites().size()); } { TF_ASSERT_OK_AND_ASSIGN(bool result, RunFlattenCallGraph(module.get())); EXPECT_TRUE(result); std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module.get()); const CallGraphNode& cond_node = call_graph->GetNode(cond_computation); EXPECT_EQ(1, cond_node.caller_callsites().size()); } }
GraphCyclesTest_LongPath
xla/service/graphcycles/graphcycles_test.cc
GraphCycles::GraphCycles() : rep_(new Rep) {} GraphCycles::~GraphCycles() { delete rep_; } bool GraphCycles::CheckInvariants() const { Rep* r = rep_; NodeSet ranks; // Set of ranks seen so far. for (size_t x = 0; x < r->nodes_.size(); x++) { Node* nx = &r->nodes_[x]; if (nx->visited) { LOG(FATAL) << "Did not clear visited marker on node " << x; } if (!ranks.insert(nx->rank).second) { LOG(FATAL) << "Duplicate occurrence of rank " << nx->rank; } NodeIO* nx_io = &r->node_io_[x]; for (int32_t y : nx_io->out.GetSequence()) { Node* ny = &r->nodes_[y]; if (nx->rank >= ny->rank) { LOG(FATAL) << "Edge " << x << "->" << y << " has bad rank assignment " << nx->rank << "->" << ny->rank; } } } return true; } int32_t GraphCycles::NewNode() { if (rep_->free_nodes_.empty()) { Node n; n.visited = false; n.rank = rep_->nodes_.size(); rep_->nodes_.emplace_back(n); rep_->node_io_.emplace_back(); rep_->node_data_.push_back(nullptr); return n.rank; } else { // Preserve preceding rank since the set of ranks in use must be // a permutation of [0,rep_->nodes_.size()-1]. int32_t r = rep_->free_nodes_.back(); rep_->free_nodes_.pop_back(); rep_->node_data_[r] = nullptr; return r; } } void GraphCycles::RemoveNode(int32_t node) { NodeIO* x = &rep_->node_io_[node]; for (int32_t y : x->out.GetSequence()) { rep_->node_io_[y].in.Erase(node); } for (int32_t y : x->in.GetSequence()) { rep_->node_io_[y].out.Erase(node); } x->in.Clear(); x->out.Clear(); rep_->free_nodes_.push_back(node); } void* GraphCycles::GetNodeData(int32_t node) const { return rep_->node_data_[node]; } void GraphCycles::SetNodeData(int32_t node, void* data) { rep_->node_data_[node] = data; } bool GraphCycles::HasEdge(int32_t x, int32_t y) const { return rep_->node_io_[x].out.Contains(y); } void GraphCycles::RemoveEdge(int32_t x, int32_t y) { rep_->node_io_[x].out.Erase(y); rep_->node_io_[y].in.Erase(x); // No need to update the rank assignment since a previous valid // rank assignment remains valid after an edge deletion. } bool GraphCycles::InsertEdge(int32_t x, int32_t y) { if (x == y) return false; Rep* r = rep_; NodeIO* nx_io = &r->node_io_[x]; if (!nx_io->out.Insert(y)) { // Edge already exists. return true; } NodeIO* ny_io = &r->node_io_[y]; ny_io->in.Insert(x); Node* nx = &r->nodes_[x]; Node* ny = &r->nodes_[y]; if (nx->rank <= ny->rank) { // New edge is consistent with existing rank assignment. return true; } // Current rank assignments are incompatible with the new edge. Recompute. // We only need to consider nodes that fall in the range [ny->rank,nx->rank]. if (!ForwardDFS(r, y, nx->rank)) { // Found a cycle. Undo the insertion and tell caller. nx_io->out.Erase(y); ny_io->in.Erase(x); // Since we do not call Reorder() on this path, clear any visited // markers left by ForwardDFS. ClearVisitedBits(r, r->deltaf_); return false; } BackwardDFS(r, x, ny->rank); Reorder(r); return true; } static bool ForwardDFS(GraphCycles::Rep* r, int32_t n, int32_t upper_bound) { // Avoid recursion since stack space might be limited. // We instead keep a stack of nodes to visit. r->deltaf_.clear(); r->stack_.clear(); r->stack_.push_back(n); while (!r->stack_.empty()) { n = r->stack_.back(); r->stack_.pop_back(); Node* nn = &r->nodes_[n]; if (nn->visited) continue; nn->visited = true; r->deltaf_.push_back(n); NodeIO* nn_io = &r->node_io_[n]; for (auto w : nn_io->out.GetSequence()) { Node* nw = &r->nodes_[w]; if (nw->rank == upper_bound) { return false; // Cycle } if (!nw->visited && nw->rank < upper_bound) { r->stack_.push_back(w); } } } return true; } static void BackwardDFS(GraphCycles::Rep* r, int32_t n, int32_t lower_bound) { r->deltab_.clear(); r->stack_.clear(); r->stack_.push_back(n); while (!r->stack_.empty()) { n = r->stack_.back(); r->stack_.pop_back(); Node* nn = &r->nodes_[n]; if (nn->visited) continue; nn->visited = true; r->deltab_.push_back(n); NodeIO* nn_io = &r->node_io_[n]; for (auto w : nn_io->in.GetSequence()) { Node* nw = &r->nodes_[w]; if (!nw->visited && lower_bound < nw->rank) { r->stack_.push_back(w); } } } } static void Reorder(GraphCycles::Rep* r) { Sort(r->nodes_, &r->deltab_); Sort(r->nodes_, &r->deltaf_); // Adds contents of delta lists to list_ (backwards deltas first). r->list_.clear(); MoveToList(r, &r->deltab_, &r->list_); MoveToList(r, &r->deltaf_, &r->list_); // Produce sorted list of all ranks that will be reassigned. r->merged_.resize(r->deltab_.size() + r->deltaf_.size()); std::merge(r->deltab_.begin(), r->deltab_.end(), r->deltaf_.begin(), r->deltaf_.end(), r->merged_.begin()); // Assign the ranks in order to the collected list. for (size_t i = 0; i < r->list_.size(); i++) { r->nodes_[r->list_[i]].rank = r->merged_[i]; } } static void Sort(absl::Span<const Node> nodes, std::vector<int32_t>* delta) { std::sort(delta->begin(), delta->end(), [&](int32_t a, int32_t b) { return nodes[a].rank < nodes[b].rank; }); } static void MoveToList(GraphCycles::Rep* r, std::vector<int32_t>* src, std::vector<int32_t>* dst) { for (size_t i = 0; i < src->size(); i++) { int32_t w = (*src)[i]; (*src)[i] = r->nodes_[w].rank; // Replace src entry with its rank r->nodes_[w].visited = false; // Prepare for future DFS calls dst->push_back(w); } } static void ClearVisitedBits(GraphCycles::Rep* r, absl::Span<const int32_t> visited_indices) { for (auto index : visited_indices) { r->nodes_[index].visited = false; } } int GraphCycles::FindPath(int32_t x, int32_t y, int max_path_len, int32_t path[]) const { // Forward depth first search starting at x until we hit y. // As we descend into a node, we push it onto the path. // As we leave a node, we remove it from the path. int path_len = 0; Rep* r = rep_; NodeSet seen; r->stack_.clear(); r->stack_.push_back(x); while (!r->stack_.empty()) { int32_t n = r->stack_.back(); r->stack_.pop_back(); if (n < 0) { // Marker to indicate that we are leaving a node path_len--; continue; } if (path_len < max_path_len) { path[path_len] = n; } path_len++; r->stack_.push_back(-1); // Will remove tentative path entry if (n == y) { return path_len; } for (auto w : r->node_io_[n].out.GetSequence()) { if (seen.insert(w).second) { r->stack_.push_back(w); } } } return 0; } bool GraphCycles::IsReachable(int32_t x, int32_t y) const { return FindPath(x, y, 0, nullptr) > 0; } bool GraphCycles::IsReachableNonConst(int32_t x, int32_t y) { if (x == y) return true; Rep* r = rep_; Node* nx = &r->nodes_[x]; Node* ny = &r->nodes_[y]; if (nx->rank >= ny->rank) { // x cannot reach y since it is after it in the topological ordering return false; } // See if x can reach y using a DFS search that is limited to y's rank bool reachable = !ForwardDFS(r, x, ny->rank); // Clear any visited markers left by ForwardDFS. ClearVisitedBits(r, r->deltaf_); return reachable; } bool GraphCycles::CanContractEdge(int32_t a, int32_t b) { CHECK(HasEdge(a, b)) << "No edge exists from " << a << " to " << b; RemoveEdge(a, b); bool reachable = IsReachableNonConst(a, b); // Restore the graph to its original state. InsertEdge(a, b); // If reachable, then contracting edge will cause cycle. return !reachable; } std::optional<int32_t> GraphCycles::ContractEdge(int32_t a, int32_t b) { CHECK(HasEdge(a, b)); RemoveEdge(a, b); if (IsReachableNonConst(a, b)) { // Restore the graph to its original state. InsertEdge(a, b); return std::nullopt; } if (rep_->node_io_[b].in.Size() + rep_->node_io_[b].out.Size() > rep_->node_io_[a].in.Size() + rep_->node_io_[a].out.Size()) { // Swap "a" and "b" to minimize copying. std::swap(a, b); } NodeIO* nb_io = &rep_->node_io_[b]; OrderedNodeSet out = std::move(nb_io->out); OrderedNodeSet in = std::move(nb_io->in); for (int32_t y : out.GetSequence()) { rep_->node_io_[y].in.Erase(b); } for (int32_t y : in.GetSequence()) { rep_->node_io_[y].out.Erase(b); } rep_->free_nodes_.push_back(b); rep_->node_io_[a].out.Reserve(rep_->node_io_[a].out.Size() + out.Size()); for (int32_t y : out.GetSequence()) { InsertEdge(a, y); } rep_->node_io_[a].in.Reserve(rep_->node_io_[a].in.Size() + in.Size()); for (int32_t y : in.GetSequence()) { InsertEdge(y, a); } // Note, if the swap happened it might be what originally was called "b". return a; } absl::Span<const int32_t> GraphCycles::Successors(int32_t node) const { return rep_->node_io_[node].out.GetSequence(); } absl::Span<const int32_t> GraphCycles::Predecessors(int32_t node) const { return rep_->node_io_[node].in.GetSequence(); } std::vector<int32_t> GraphCycles::SuccessorsCopy(int32_t node) const { absl::Span<const int32_t> successors = Successors(node); return std::vector<int32_t>(successors.begin(), successors.end()); } std::vector<int32_t> GraphCycles::PredecessorsCopy(int32_t node) const { absl::Span<const int32_t> predecessors = Predecessors(node); return std::vector<int32_t>(predecessors.begin(), predecessors.end()); } std::vector<int32_t> GraphCycles::AllNodesInPostOrder() const { absl::flat_hash_set<int32_t> free_nodes_set; absl::c_copy(rep_->free_nodes_, std::inserter(free_nodes_set, free_nodes_set.begin())); std::vector<int32_t> all_nodes; all_nodes.reserve(rep_->nodes_.size() - free_nodes_set.size()); for (int64_t i = 0, e = rep_->nodes_.size(); i < e; i++) { if (!free_nodes_set.contains(i)) { all_nodes.push_back(i); } } SortInPostOrder(rep_->nodes_, &all_nodes); return all_nodes; } std::string GraphCycles::DebugString() const { absl::flat_hash_set<int32_t> free_nodes_set(rep_->free_nodes_.begin(), rep_->free_nodes_.end()); std::string result = "digraph {\n"; for (int i = 0, end = rep_->nodes_.size(); i < end; i++) { if (free_nodes_set.contains(i)) { continue; } for (int32_t succ : rep_->node_io_[i].out.GetSequence()) { absl::StrAppend(&result, " \"", i, "\" -> \"", succ, "\"\n"); } } absl::StrAppend(&result, "}\n"); return result; }
#include "xla/service/graphcycles/graphcycles.h" #include <cstdint> #include <optional> #include <random> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/random/random.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" class GraphCyclesTest : public ::testing::Test { public: tensorflow::GraphCycles g_; // Test relies on ith NewNode() call returning Node numbered i GraphCyclesTest() { for (int i = 0; i < 100; i++) { CHECK_EQ(i, g_.NewNode()); } CHECK(g_.CheckInvariants()); } bool AddEdge(int x, int y) { return g_.InsertEdge(x, y); } void AddMultiples() { // For every node x > 0: add edge to 2*x, 3*x for (int x = 1; x < 25; x++) { EXPECT_TRUE(AddEdge(x, 2 * x)) << x; EXPECT_TRUE(AddEdge(x, 3 * x)) << x; } CHECK(g_.CheckInvariants()); } std::string Path(int x, int y) { static const int kPathSize = 5; int32_t path[kPathSize]; int np = g_.FindPath(x, y, kPathSize, path); std::string result; for (int i = 0; i < np; i++) { if (i >= kPathSize) { result += " ..."; break; } if (!result.empty()) result.push_back(' '); char buf[20]; snprintf(buf, sizeof(buf), "%d", path[i]); result += buf; } return result; } }; TEST_F(GraphCyclesTest, LongPath) { ASSERT_TRUE(AddEdge(2, 4)); ASSERT_TRUE(AddEdge(4, 6)); ASSERT_TRUE(AddEdge(6, 8)); ASSERT_TRUE(AddEdge(8, 10)); ASSERT_TRUE(AddEdge(10, 12)); ASSERT_FALSE(AddEdge(12, 2)); EXPECT_EQ("2 4 6 8 10 ...", Path(2, 12)); CHECK(g_.CheckInvariants()); }
GraphCyclesTest_ManyEdges
xla/service/graphcycles/graphcycles_test.cc
GraphCycles::GraphCycles() : rep_(new Rep) {} GraphCycles::~GraphCycles() { delete rep_; } bool GraphCycles::CheckInvariants() const { Rep* r = rep_; NodeSet ranks; // Set of ranks seen so far. for (size_t x = 0; x < r->nodes_.size(); x++) { Node* nx = &r->nodes_[x]; if (nx->visited) { LOG(FATAL) << "Did not clear visited marker on node " << x; } if (!ranks.insert(nx->rank).second) { LOG(FATAL) << "Duplicate occurrence of rank " << nx->rank; } NodeIO* nx_io = &r->node_io_[x]; for (int32_t y : nx_io->out.GetSequence()) { Node* ny = &r->nodes_[y]; if (nx->rank >= ny->rank) { LOG(FATAL) << "Edge " << x << "->" << y << " has bad rank assignment " << nx->rank << "->" << ny->rank; } } } return true; } int32_t GraphCycles::NewNode() { if (rep_->free_nodes_.empty()) { Node n; n.visited = false; n.rank = rep_->nodes_.size(); rep_->nodes_.emplace_back(n); rep_->node_io_.emplace_back(); rep_->node_data_.push_back(nullptr); return n.rank; } else { // Preserve preceding rank since the set of ranks in use must be // a permutation of [0,rep_->nodes_.size()-1]. int32_t r = rep_->free_nodes_.back(); rep_->free_nodes_.pop_back(); rep_->node_data_[r] = nullptr; return r; } } void GraphCycles::RemoveNode(int32_t node) { NodeIO* x = &rep_->node_io_[node]; for (int32_t y : x->out.GetSequence()) { rep_->node_io_[y].in.Erase(node); } for (int32_t y : x->in.GetSequence()) { rep_->node_io_[y].out.Erase(node); } x->in.Clear(); x->out.Clear(); rep_->free_nodes_.push_back(node); } void* GraphCycles::GetNodeData(int32_t node) const { return rep_->node_data_[node]; } void GraphCycles::SetNodeData(int32_t node, void* data) { rep_->node_data_[node] = data; } bool GraphCycles::HasEdge(int32_t x, int32_t y) const { return rep_->node_io_[x].out.Contains(y); } void GraphCycles::RemoveEdge(int32_t x, int32_t y) { rep_->node_io_[x].out.Erase(y); rep_->node_io_[y].in.Erase(x); // No need to update the rank assignment since a previous valid // rank assignment remains valid after an edge deletion. } bool GraphCycles::InsertEdge(int32_t x, int32_t y) { if (x == y) return false; Rep* r = rep_; NodeIO* nx_io = &r->node_io_[x]; if (!nx_io->out.Insert(y)) { // Edge already exists. return true; } NodeIO* ny_io = &r->node_io_[y]; ny_io->in.Insert(x); Node* nx = &r->nodes_[x]; Node* ny = &r->nodes_[y]; if (nx->rank <= ny->rank) { // New edge is consistent with existing rank assignment. return true; } // Current rank assignments are incompatible with the new edge. Recompute. // We only need to consider nodes that fall in the range [ny->rank,nx->rank]. if (!ForwardDFS(r, y, nx->rank)) { // Found a cycle. Undo the insertion and tell caller. nx_io->out.Erase(y); ny_io->in.Erase(x); // Since we do not call Reorder() on this path, clear any visited // markers left by ForwardDFS. ClearVisitedBits(r, r->deltaf_); return false; } BackwardDFS(r, x, ny->rank); Reorder(r); return true; } static bool ForwardDFS(GraphCycles::Rep* r, int32_t n, int32_t upper_bound) { // Avoid recursion since stack space might be limited. // We instead keep a stack of nodes to visit. r->deltaf_.clear(); r->stack_.clear(); r->stack_.push_back(n); while (!r->stack_.empty()) { n = r->stack_.back(); r->stack_.pop_back(); Node* nn = &r->nodes_[n]; if (nn->visited) continue; nn->visited = true; r->deltaf_.push_back(n); NodeIO* nn_io = &r->node_io_[n]; for (auto w : nn_io->out.GetSequence()) { Node* nw = &r->nodes_[w]; if (nw->rank == upper_bound) { return false; // Cycle } if (!nw->visited && nw->rank < upper_bound) { r->stack_.push_back(w); } } } return true; } static void BackwardDFS(GraphCycles::Rep* r, int32_t n, int32_t lower_bound) { r->deltab_.clear(); r->stack_.clear(); r->stack_.push_back(n); while (!r->stack_.empty()) { n = r->stack_.back(); r->stack_.pop_back(); Node* nn = &r->nodes_[n]; if (nn->visited) continue; nn->visited = true; r->deltab_.push_back(n); NodeIO* nn_io = &r->node_io_[n]; for (auto w : nn_io->in.GetSequence()) { Node* nw = &r->nodes_[w]; if (!nw->visited && lower_bound < nw->rank) { r->stack_.push_back(w); } } } } static void Reorder(GraphCycles::Rep* r) { Sort(r->nodes_, &r->deltab_); Sort(r->nodes_, &r->deltaf_); // Adds contents of delta lists to list_ (backwards deltas first). r->list_.clear(); MoveToList(r, &r->deltab_, &r->list_); MoveToList(r, &r->deltaf_, &r->list_); // Produce sorted list of all ranks that will be reassigned. r->merged_.resize(r->deltab_.size() + r->deltaf_.size()); std::merge(r->deltab_.begin(), r->deltab_.end(), r->deltaf_.begin(), r->deltaf_.end(), r->merged_.begin()); // Assign the ranks in order to the collected list. for (size_t i = 0; i < r->list_.size(); i++) { r->nodes_[r->list_[i]].rank = r->merged_[i]; } } static void Sort(absl::Span<const Node> nodes, std::vector<int32_t>* delta) { std::sort(delta->begin(), delta->end(), [&](int32_t a, int32_t b) { return nodes[a].rank < nodes[b].rank; }); } static void MoveToList(GraphCycles::Rep* r, std::vector<int32_t>* src, std::vector<int32_t>* dst) { for (size_t i = 0; i < src->size(); i++) { int32_t w = (*src)[i]; (*src)[i] = r->nodes_[w].rank; // Replace src entry with its rank r->nodes_[w].visited = false; // Prepare for future DFS calls dst->push_back(w); } } static void ClearVisitedBits(GraphCycles::Rep* r, absl::Span<const int32_t> visited_indices) { for (auto index : visited_indices) { r->nodes_[index].visited = false; } } int GraphCycles::FindPath(int32_t x, int32_t y, int max_path_len, int32_t path[]) const { // Forward depth first search starting at x until we hit y. // As we descend into a node, we push it onto the path. // As we leave a node, we remove it from the path. int path_len = 0; Rep* r = rep_; NodeSet seen; r->stack_.clear(); r->stack_.push_back(x); while (!r->stack_.empty()) { int32_t n = r->stack_.back(); r->stack_.pop_back(); if (n < 0) { // Marker to indicate that we are leaving a node path_len--; continue; } if (path_len < max_path_len) { path[path_len] = n; } path_len++; r->stack_.push_back(-1); // Will remove tentative path entry if (n == y) { return path_len; } for (auto w : r->node_io_[n].out.GetSequence()) { if (seen.insert(w).second) { r->stack_.push_back(w); } } } return 0; } bool GraphCycles::IsReachable(int32_t x, int32_t y) const { return FindPath(x, y, 0, nullptr) > 0; } bool GraphCycles::IsReachableNonConst(int32_t x, int32_t y) { if (x == y) return true; Rep* r = rep_; Node* nx = &r->nodes_[x]; Node* ny = &r->nodes_[y]; if (nx->rank >= ny->rank) { // x cannot reach y since it is after it in the topological ordering return false; } // See if x can reach y using a DFS search that is limited to y's rank bool reachable = !ForwardDFS(r, x, ny->rank); // Clear any visited markers left by ForwardDFS. ClearVisitedBits(r, r->deltaf_); return reachable; } bool GraphCycles::CanContractEdge(int32_t a, int32_t b) { CHECK(HasEdge(a, b)) << "No edge exists from " << a << " to " << b; RemoveEdge(a, b); bool reachable = IsReachableNonConst(a, b); // Restore the graph to its original state. InsertEdge(a, b); // If reachable, then contracting edge will cause cycle. return !reachable; } std::optional<int32_t> GraphCycles::ContractEdge(int32_t a, int32_t b) { CHECK(HasEdge(a, b)); RemoveEdge(a, b); if (IsReachableNonConst(a, b)) { // Restore the graph to its original state. InsertEdge(a, b); return std::nullopt; } if (rep_->node_io_[b].in.Size() + rep_->node_io_[b].out.Size() > rep_->node_io_[a].in.Size() + rep_->node_io_[a].out.Size()) { // Swap "a" and "b" to minimize copying. std::swap(a, b); } NodeIO* nb_io = &rep_->node_io_[b]; OrderedNodeSet out = std::move(nb_io->out); OrderedNodeSet in = std::move(nb_io->in); for (int32_t y : out.GetSequence()) { rep_->node_io_[y].in.Erase(b); } for (int32_t y : in.GetSequence()) { rep_->node_io_[y].out.Erase(b); } rep_->free_nodes_.push_back(b); rep_->node_io_[a].out.Reserve(rep_->node_io_[a].out.Size() + out.Size()); for (int32_t y : out.GetSequence()) { InsertEdge(a, y); } rep_->node_io_[a].in.Reserve(rep_->node_io_[a].in.Size() + in.Size()); for (int32_t y : in.GetSequence()) { InsertEdge(y, a); } // Note, if the swap happened it might be what originally was called "b". return a; } absl::Span<const int32_t> GraphCycles::Successors(int32_t node) const { return rep_->node_io_[node].out.GetSequence(); } absl::Span<const int32_t> GraphCycles::Predecessors(int32_t node) const { return rep_->node_io_[node].in.GetSequence(); } std::vector<int32_t> GraphCycles::SuccessorsCopy(int32_t node) const { absl::Span<const int32_t> successors = Successors(node); return std::vector<int32_t>(successors.begin(), successors.end()); } std::vector<int32_t> GraphCycles::PredecessorsCopy(int32_t node) const { absl::Span<const int32_t> predecessors = Predecessors(node); return std::vector<int32_t>(predecessors.begin(), predecessors.end()); } std::vector<int32_t> GraphCycles::AllNodesInPostOrder() const { absl::flat_hash_set<int32_t> free_nodes_set; absl::c_copy(rep_->free_nodes_, std::inserter(free_nodes_set, free_nodes_set.begin())); std::vector<int32_t> all_nodes; all_nodes.reserve(rep_->nodes_.size() - free_nodes_set.size()); for (int64_t i = 0, e = rep_->nodes_.size(); i < e; i++) { if (!free_nodes_set.contains(i)) { all_nodes.push_back(i); } } SortInPostOrder(rep_->nodes_, &all_nodes); return all_nodes; } std::string GraphCycles::DebugString() const { absl::flat_hash_set<int32_t> free_nodes_set(rep_->free_nodes_.begin(), rep_->free_nodes_.end()); std::string result = "digraph {\n"; for (int i = 0, end = rep_->nodes_.size(); i < end; i++) { if (free_nodes_set.contains(i)) { continue; } for (int32_t succ : rep_->node_io_[i].out.GetSequence()) { absl::StrAppend(&result, " \"", i, "\" -> \"", succ, "\"\n"); } } absl::StrAppend(&result, "}\n"); return result; }
#include "xla/service/graphcycles/graphcycles.h" #include <cstdint> #include <optional> #include <random> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/random/random.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" class GraphCyclesTest : public ::testing::Test { public: tensorflow::GraphCycles g_; // Test relies on ith NewNode() call returning Node numbered i GraphCyclesTest() { for (int i = 0; i < 100; i++) { CHECK_EQ(i, g_.NewNode()); } CHECK(g_.CheckInvariants()); } bool AddEdge(int x, int y) { return g_.InsertEdge(x, y); } void AddMultiples() { // For every node x > 0: add edge to 2*x, 3*x for (int x = 1; x < 25; x++) { EXPECT_TRUE(AddEdge(x, 2 * x)) << x; EXPECT_TRUE(AddEdge(x, 3 * x)) << x; } CHECK(g_.CheckInvariants()); } std::string Path(int x, int y) { static const int kPathSize = 5; int32_t path[kPathSize]; int np = g_.FindPath(x, y, kPathSize, path); std::string result; for (int i = 0; i < np; i++) { if (i >= kPathSize) { result += " ..."; break; } if (!result.empty()) result.push_back(' '); char buf[20]; snprintf(buf, sizeof(buf), "%d", path[i]); result += buf; } return result; } }; TEST_F(GraphCyclesTest, ManyEdges) { const int N = 50; for (int i = 0; i < N; i++) { for (int j = 1; j < N; j++) { ASSERT_TRUE(AddEdge(i, i + j)); } } CHECK(g_.CheckInvariants()); ASSERT_TRUE(AddEdge(2 * N - 1, 0)); CHECK(g_.CheckInvariants()); ASSERT_FALSE(AddEdge(10, 9)); CHECK(g_.CheckInvariants()); }
GraphCyclesTest_RemoveNode
xla/service/graphcycles/graphcycles_test.cc
GraphCycles::GraphCycles() : rep_(new Rep) {} GraphCycles::~GraphCycles() { delete rep_; } bool GraphCycles::CheckInvariants() const { Rep* r = rep_; NodeSet ranks; // Set of ranks seen so far. for (size_t x = 0; x < r->nodes_.size(); x++) { Node* nx = &r->nodes_[x]; if (nx->visited) { LOG(FATAL) << "Did not clear visited marker on node " << x; } if (!ranks.insert(nx->rank).second) { LOG(FATAL) << "Duplicate occurrence of rank " << nx->rank; } NodeIO* nx_io = &r->node_io_[x]; for (int32_t y : nx_io->out.GetSequence()) { Node* ny = &r->nodes_[y]; if (nx->rank >= ny->rank) { LOG(FATAL) << "Edge " << x << "->" << y << " has bad rank assignment " << nx->rank << "->" << ny->rank; } } } return true; } int32_t GraphCycles::NewNode() { if (rep_->free_nodes_.empty()) { Node n; n.visited = false; n.rank = rep_->nodes_.size(); rep_->nodes_.emplace_back(n); rep_->node_io_.emplace_back(); rep_->node_data_.push_back(nullptr); return n.rank; } else { // Preserve preceding rank since the set of ranks in use must be // a permutation of [0,rep_->nodes_.size()-1]. int32_t r = rep_->free_nodes_.back(); rep_->free_nodes_.pop_back(); rep_->node_data_[r] = nullptr; return r; } } void GraphCycles::RemoveNode(int32_t node) { NodeIO* x = &rep_->node_io_[node]; for (int32_t y : x->out.GetSequence()) { rep_->node_io_[y].in.Erase(node); } for (int32_t y : x->in.GetSequence()) { rep_->node_io_[y].out.Erase(node); } x->in.Clear(); x->out.Clear(); rep_->free_nodes_.push_back(node); } void* GraphCycles::GetNodeData(int32_t node) const { return rep_->node_data_[node]; } void GraphCycles::SetNodeData(int32_t node, void* data) { rep_->node_data_[node] = data; } bool GraphCycles::HasEdge(int32_t x, int32_t y) const { return rep_->node_io_[x].out.Contains(y); } void GraphCycles::RemoveEdge(int32_t x, int32_t y) { rep_->node_io_[x].out.Erase(y); rep_->node_io_[y].in.Erase(x); // No need to update the rank assignment since a previous valid // rank assignment remains valid after an edge deletion. } bool GraphCycles::InsertEdge(int32_t x, int32_t y) { if (x == y) return false; Rep* r = rep_; NodeIO* nx_io = &r->node_io_[x]; if (!nx_io->out.Insert(y)) { // Edge already exists. return true; } NodeIO* ny_io = &r->node_io_[y]; ny_io->in.Insert(x); Node* nx = &r->nodes_[x]; Node* ny = &r->nodes_[y]; if (nx->rank <= ny->rank) { // New edge is consistent with existing rank assignment. return true; } // Current rank assignments are incompatible with the new edge. Recompute. // We only need to consider nodes that fall in the range [ny->rank,nx->rank]. if (!ForwardDFS(r, y, nx->rank)) { // Found a cycle. Undo the insertion and tell caller. nx_io->out.Erase(y); ny_io->in.Erase(x); // Since we do not call Reorder() on this path, clear any visited // markers left by ForwardDFS. ClearVisitedBits(r, r->deltaf_); return false; } BackwardDFS(r, x, ny->rank); Reorder(r); return true; } static bool ForwardDFS(GraphCycles::Rep* r, int32_t n, int32_t upper_bound) { // Avoid recursion since stack space might be limited. // We instead keep a stack of nodes to visit. r->deltaf_.clear(); r->stack_.clear(); r->stack_.push_back(n); while (!r->stack_.empty()) { n = r->stack_.back(); r->stack_.pop_back(); Node* nn = &r->nodes_[n]; if (nn->visited) continue; nn->visited = true; r->deltaf_.push_back(n); NodeIO* nn_io = &r->node_io_[n]; for (auto w : nn_io->out.GetSequence()) { Node* nw = &r->nodes_[w]; if (nw->rank == upper_bound) { return false; // Cycle } if (!nw->visited && nw->rank < upper_bound) { r->stack_.push_back(w); } } } return true; } static void BackwardDFS(GraphCycles::Rep* r, int32_t n, int32_t lower_bound) { r->deltab_.clear(); r->stack_.clear(); r->stack_.push_back(n); while (!r->stack_.empty()) { n = r->stack_.back(); r->stack_.pop_back(); Node* nn = &r->nodes_[n]; if (nn->visited) continue; nn->visited = true; r->deltab_.push_back(n); NodeIO* nn_io = &r->node_io_[n]; for (auto w : nn_io->in.GetSequence()) { Node* nw = &r->nodes_[w]; if (!nw->visited && lower_bound < nw->rank) { r->stack_.push_back(w); } } } } static void Reorder(GraphCycles::Rep* r) { Sort(r->nodes_, &r->deltab_); Sort(r->nodes_, &r->deltaf_); // Adds contents of delta lists to list_ (backwards deltas first). r->list_.clear(); MoveToList(r, &r->deltab_, &r->list_); MoveToList(r, &r->deltaf_, &r->list_); // Produce sorted list of all ranks that will be reassigned. r->merged_.resize(r->deltab_.size() + r->deltaf_.size()); std::merge(r->deltab_.begin(), r->deltab_.end(), r->deltaf_.begin(), r->deltaf_.end(), r->merged_.begin()); // Assign the ranks in order to the collected list. for (size_t i = 0; i < r->list_.size(); i++) { r->nodes_[r->list_[i]].rank = r->merged_[i]; } } static void Sort(absl::Span<const Node> nodes, std::vector<int32_t>* delta) { std::sort(delta->begin(), delta->end(), [&](int32_t a, int32_t b) { return nodes[a].rank < nodes[b].rank; }); } static void MoveToList(GraphCycles::Rep* r, std::vector<int32_t>* src, std::vector<int32_t>* dst) { for (size_t i = 0; i < src->size(); i++) { int32_t w = (*src)[i]; (*src)[i] = r->nodes_[w].rank; // Replace src entry with its rank r->nodes_[w].visited = false; // Prepare for future DFS calls dst->push_back(w); } } static void ClearVisitedBits(GraphCycles::Rep* r, absl::Span<const int32_t> visited_indices) { for (auto index : visited_indices) { r->nodes_[index].visited = false; } } int GraphCycles::FindPath(int32_t x, int32_t y, int max_path_len, int32_t path[]) const { // Forward depth first search starting at x until we hit y. // As we descend into a node, we push it onto the path. // As we leave a node, we remove it from the path. int path_len = 0; Rep* r = rep_; NodeSet seen; r->stack_.clear(); r->stack_.push_back(x); while (!r->stack_.empty()) { int32_t n = r->stack_.back(); r->stack_.pop_back(); if (n < 0) { // Marker to indicate that we are leaving a node path_len--; continue; } if (path_len < max_path_len) { path[path_len] = n; } path_len++; r->stack_.push_back(-1); // Will remove tentative path entry if (n == y) { return path_len; } for (auto w : r->node_io_[n].out.GetSequence()) { if (seen.insert(w).second) { r->stack_.push_back(w); } } } return 0; } bool GraphCycles::IsReachable(int32_t x, int32_t y) const { return FindPath(x, y, 0, nullptr) > 0; } bool GraphCycles::IsReachableNonConst(int32_t x, int32_t y) { if (x == y) return true; Rep* r = rep_; Node* nx = &r->nodes_[x]; Node* ny = &r->nodes_[y]; if (nx->rank >= ny->rank) { // x cannot reach y since it is after it in the topological ordering return false; } // See if x can reach y using a DFS search that is limited to y's rank bool reachable = !ForwardDFS(r, x, ny->rank); // Clear any visited markers left by ForwardDFS. ClearVisitedBits(r, r->deltaf_); return reachable; } bool GraphCycles::CanContractEdge(int32_t a, int32_t b) { CHECK(HasEdge(a, b)) << "No edge exists from " << a << " to " << b; RemoveEdge(a, b); bool reachable = IsReachableNonConst(a, b); // Restore the graph to its original state. InsertEdge(a, b); // If reachable, then contracting edge will cause cycle. return !reachable; } std::optional<int32_t> GraphCycles::ContractEdge(int32_t a, int32_t b) { CHECK(HasEdge(a, b)); RemoveEdge(a, b); if (IsReachableNonConst(a, b)) { // Restore the graph to its original state. InsertEdge(a, b); return std::nullopt; } if (rep_->node_io_[b].in.Size() + rep_->node_io_[b].out.Size() > rep_->node_io_[a].in.Size() + rep_->node_io_[a].out.Size()) { // Swap "a" and "b" to minimize copying. std::swap(a, b); } NodeIO* nb_io = &rep_->node_io_[b]; OrderedNodeSet out = std::move(nb_io->out); OrderedNodeSet in = std::move(nb_io->in); for (int32_t y : out.GetSequence()) { rep_->node_io_[y].in.Erase(b); } for (int32_t y : in.GetSequence()) { rep_->node_io_[y].out.Erase(b); } rep_->free_nodes_.push_back(b); rep_->node_io_[a].out.Reserve(rep_->node_io_[a].out.Size() + out.Size()); for (int32_t y : out.GetSequence()) { InsertEdge(a, y); } rep_->node_io_[a].in.Reserve(rep_->node_io_[a].in.Size() + in.Size()); for (int32_t y : in.GetSequence()) { InsertEdge(y, a); } // Note, if the swap happened it might be what originally was called "b". return a; } absl::Span<const int32_t> GraphCycles::Successors(int32_t node) const { return rep_->node_io_[node].out.GetSequence(); } absl::Span<const int32_t> GraphCycles::Predecessors(int32_t node) const { return rep_->node_io_[node].in.GetSequence(); } std::vector<int32_t> GraphCycles::SuccessorsCopy(int32_t node) const { absl::Span<const int32_t> successors = Successors(node); return std::vector<int32_t>(successors.begin(), successors.end()); } std::vector<int32_t> GraphCycles::PredecessorsCopy(int32_t node) const { absl::Span<const int32_t> predecessors = Predecessors(node); return std::vector<int32_t>(predecessors.begin(), predecessors.end()); } std::vector<int32_t> GraphCycles::AllNodesInPostOrder() const { absl::flat_hash_set<int32_t> free_nodes_set; absl::c_copy(rep_->free_nodes_, std::inserter(free_nodes_set, free_nodes_set.begin())); std::vector<int32_t> all_nodes; all_nodes.reserve(rep_->nodes_.size() - free_nodes_set.size()); for (int64_t i = 0, e = rep_->nodes_.size(); i < e; i++) { if (!free_nodes_set.contains(i)) { all_nodes.push_back(i); } } SortInPostOrder(rep_->nodes_, &all_nodes); return all_nodes; } std::string GraphCycles::DebugString() const { absl::flat_hash_set<int32_t> free_nodes_set(rep_->free_nodes_.begin(), rep_->free_nodes_.end()); std::string result = "digraph {\n"; for (int i = 0, end = rep_->nodes_.size(); i < end; i++) { if (free_nodes_set.contains(i)) { continue; } for (int32_t succ : rep_->node_io_[i].out.GetSequence()) { absl::StrAppend(&result, " \"", i, "\" -> \"", succ, "\"\n"); } } absl::StrAppend(&result, "}\n"); return result; }
#include "xla/service/graphcycles/graphcycles.h" #include <cstdint> #include <optional> #include <random> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/random/random.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" class GraphCyclesTest : public ::testing::Test { public: tensorflow::GraphCycles g_; // Test relies on ith NewNode() call returning Node numbered i GraphCyclesTest() { for (int i = 0; i < 100; i++) { CHECK_EQ(i, g_.NewNode()); } CHECK(g_.CheckInvariants()); } bool AddEdge(int x, int y) { return g_.InsertEdge(x, y); } void AddMultiples() { // For every node x > 0: add edge to 2*x, 3*x for (int x = 1; x < 25; x++) { EXPECT_TRUE(AddEdge(x, 2 * x)) << x; EXPECT_TRUE(AddEdge(x, 3 * x)) << x; } CHECK(g_.CheckInvariants()); } std::string Path(int x, int y) { static const int kPathSize = 5; int32_t path[kPathSize]; int np = g_.FindPath(x, y, kPathSize, path); std::string result; for (int i = 0; i < np; i++) { if (i >= kPathSize) { result += " ..."; break; } if (!result.empty()) result.push_back(' '); char buf[20]; snprintf(buf, sizeof(buf), "%d", path[i]); result += buf; } return result; } }; TEST_F(GraphCyclesTest, RemoveNode) { ASSERT_TRUE(AddEdge(1, 2)); ASSERT_TRUE(AddEdge(2, 3)); ASSERT_TRUE(AddEdge(3, 4)); ASSERT_TRUE(AddEdge(4, 5)); g_.RemoveNode(3); ASSERT_TRUE(AddEdge(5, 1)); }
HloExecutionProfileTest_Basic
xla/service/hlo_execution_profile_test.cc
HloProfileIndexMap::HloProfileIndexMap( const HloModule& module, absl::Span<const std::string> extra_metrics) { size_t current_profile_index = 0; for (xla::HloComputation* computation : module.MakeComputationPostOrder()) { InsertOrDie(&computation_to_profile_idx_, computation, current_profile_index++); for (const HloInstruction* instruction : computation->instructions()) { // For simplicity we track all instructions here, but we could skip // non-executing instructions like constants and parameters. InsertOrDie(&instruction_to_profile_idx_, instruction, current_profile_index++); } } for (const std::string& key : extra_metrics) { InsertOrDie(&extra_metric_to_profile_idx_, key, current_profile_index++); } } std::unique_ptr<HloProfilePrinterData> CreateHloProfilePrinterData( const HloProfileIndexMap& hlo_profile_index_map, const HloCostAnalysis& cost_analysis, absl::string_view entry_computation_name) { using HloComputationInfo = HloProfilePrinterData::HloComputationInfo; using HloInstructionInfo = HloProfilePrinterData::HloInstructionInfo; size_t profile_counters_size = hlo_profile_index_map.total_count(); std::unique_ptr<HloProfilePrinterData> profile_printer_data = std::make_unique<HloProfilePrinterData>(); profile_printer_data->set_profile_counters_size(profile_counters_size); profile_printer_data->mutable_computation_infos()->Reserve( hlo_profile_index_map.computation_count()); const auto& computation_to_profile_idx_map = hlo_profile_index_map.computation_to_profile_idx(); // computation_to_profile_idx_map's order is not deterministic so create a // deterministic computation_and_profile_idx_list so that we end up with a // deterministic HloProfilePrinterData protobuf. std::vector<std::pair<const HloComputation*, int64_t>> computation_and_profile_idx_list(computation_to_profile_idx_map.begin(), computation_to_profile_idx_map.end()); // The profile indices were computed deterministically in // HloProfileIndexMap::HloProfileIndexMap. absl::c_sort(computation_and_profile_idx_list, [](const std::pair<const HloComputation*, int64_t>& left, const std::pair<const HloComputation*, int64_t>& right) { return left.second < right.second; }); for (const auto& pair : computation_and_profile_idx_list) { CHECK_LT(pair.second, profile_counters_size); const HloComputation* computation = pair.first; HloComputationInfo* computation_info = profile_printer_data->add_computation_infos(); *computation_info->mutable_name() = std::string(computation->name()); computation_info->set_profile_index(pair.second); computation_info->mutable_instruction_infos()->Reserve( computation->instruction_count()); for (const HloInstruction* hlo : computation->instructions()) { HloInstructionInfo* instruction_info = computation_info->add_instruction_infos(); instruction_info->set_long_name(hlo->ToString()); instruction_info->set_short_name(hlo->ToString( HloPrintOptions().set_compact_operands(true).set_print_operand_names( false))); instruction_info->set_category(hlo->ToCategory()); instruction_info->set_flop_count(cost_analysis.flop_count(*hlo)); instruction_info->set_transcendental_count( cost_analysis.transcendental_count(*hlo)); instruction_info->set_bytes_accessed(cost_analysis.bytes_accessed(*hlo)); instruction_info->set_optimal_seconds( cost_analysis.optimal_seconds(*hlo)); instruction_info->set_profile_index( hlo_profile_index_map.GetProfileIndexFor(*hlo)); } } // Add extra metrics if any. for (const auto& pair : hlo_profile_index_map.extra_metric_to_profile_idx()) { profile_printer_data->mutable_extra_metrics()->insert( {pair.first, pair.second}); } *profile_printer_data->mutable_entry_computation() = std::string(entry_computation_name); return profile_printer_data; } HloExecutionProfile::HloExecutionProfile( const HloProfilePrinterData* hlo_profile_printer_data, const HloProfileIndexMap* hlo_profile_index_map) : hlo_profile_printer_data_(*hlo_profile_printer_data), hlo_profile_index_map_(*hlo_profile_index_map), profile_counters_( /*count=*/hlo_profile_index_map_.total_count(), /*value=*/0) {} void HloExecutionProfile::SetCyclesTakenBy(const HloInstruction* hlo, uint64_t cycles_taken) { SetCyclesTakenBy(hlo_profile_index_map_.GetProfileIndexFor(*hlo), cycles_taken); } void HloExecutionProfile::SetCyclesTakenBy(size_t index, uint64_t cycles_taken) { profile_counters_[index] = cycles_taken; } uint64_t HloExecutionProfile::GetCyclesTakenBy( const HloInstruction& hlo) const { return GetCyclesTakenBy(hlo_profile_index_map_.GetProfileIndexFor(hlo)); } uint64_t HloExecutionProfile::GetCyclesTakenBy(size_t index) const { return profile_counters_[index]; } HloExecutionProfileData HloExecutionProfile::ToProto() const { HloExecutionProfileData hlo_execution_profile_data; hlo_execution_profile_data.mutable_profile_counters()->Reserve( profile_counters_.size()); for (const auto& counter : profile_counters_) { hlo_execution_profile_data.add_profile_counters(counter); } *(hlo_execution_profile_data.mutable_printer_data()) = hlo_profile_printer_data_; return hlo_execution_profile_data; }
#include "xla/service/hlo_execution_profile.h" #include "absl/strings/str_cat.h" #include "xla/service/hlo_cost_analysis.h" #include "xla/tests/hlo_test_base.h" class HloExecutionProfileTest : public HloTestBase {}; TEST_F(HloExecutionProfileTest, Basic) { auto hlo_module = ParseAndReturnVerifiedModule(R"( HloModule test_module ENTRY entry_computation { lhs = f32[30,30]{1,0} parameter(0) rhs = f32[30,30]{1,0} parameter(1) add = f32[30,30]{1,0} add(lhs, rhs) ROOT dot = f32[30,30]{1,0} dot(lhs, add), lhs_contracting_dims={1}, rhs_contracting_dims={0} })") .value(); const HloInstruction* dot_instruction = hlo_module->entry_computation()->root_instruction(); const HloInstruction* add_instruction = dot_instruction->operand(1); Shape shape = ShapeUtil::MakeShape(F32, {30, 30}); auto shape_size_function = [&](const Shape& shape) { const int64_t pointer_size = 8; if (shape.IsOpaque()) { return pointer_size; } return ShapeUtil::ByteSizeOf(shape, pointer_size); }; HloCostAnalysis cost_analysis(shape_size_function); HloProfileIndexMap profile_index_map(*hlo_module); std::unique_ptr<HloProfilePrinterData> profile_printer = CreateHloProfilePrinterData(profile_index_map, cost_analysis, hlo_module->entry_computation()->name()); HloExecutionProfile execution_profile(profile_printer.get(), &profile_index_map); const int64_t add_cycles = 1000; const int64_t dot_cycles = 4000; execution_profile.SetCyclesTakenBy(add_instruction, add_cycles); execution_profile.SetCyclesTakenBy(dot_instruction, dot_cycles); float clock_rate_ghz = backend() .default_stream_executor() ->GetDeviceDescription() .clock_rate_ghz(); EXPECT_THAT(execution_profile.ToString(clock_rate_ghz), AllOf(ContainsRegex(StrCat(dot_cycles, " cycles.*%", dot_instruction->name())), ContainsRegex(StrCat(add_cycles, " cycles.*%", add_instruction->name())))); }
HloLivenessAnalysisTest_AddAtEntryRoot
xla/service/hlo_liveness_analysis_test.cc
void AddToWorklist(const HloInstruction* instruction, Worklist* worklist, Workset* workset) { if (workset->insert(instruction).second) { worklist->push_back(instruction); VLOG(3) << "ADD instruction: " << instruction->name(); } } VLOG(3) << "ADD instruction: " << instruction->name(); void MarkLiveAtIndex(const HloInstruction* instruction, const ShapeIndex& shape_index, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/false); } bool& alive = *liveness->mutable_element(shape_index); if (!alive) { AddToWorklist(instruction, worklist, workset); alive = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << shape_index; } } VLOG(3) << "MARK instruction: " << instruction->name() void MarkLiveAtAllIndices(const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { bool add_to_worklist = false; std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/true); add_to_worklist = true; } else { for (auto& entry : *liveness) { if (!entry.second) { add_to_worklist = true; entry.second = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << entry.first; } } } if (add_to_worklist) { AddToWorklist(instruction, worklist, workset); } } VLOG(3) << "MARK instruction: " << instruction->name() void PropagateLivenessThroughTuple( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kTuple); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughGTE( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kGetTupleElement); // Mark operand top-level index. MarkLiveAtIndex(instruction->operand(0), {}, live_index_map, worklist, workset); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); // Propagate live shape indices along GTE -> Tuple edge. ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughWhile( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kWhile); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); // Propagate liveness to while condition computation root instruction. MarkLiveAtIndex(instruction->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessToParameterCallers( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { CHECK_EQ(instruction->opcode(), HloOpcode::kParameter); const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { if (callsite.instruction()->opcode() == HloOpcode::kWhile) { auto* xla_while = callsite.instruction(); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughControlFlow( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { HloInstruction* caller = callsite.instruction(); if (caller->opcode() == HloOpcode::kWhile) { // If a live instruction is within the %while body or condition // computation, mark the predicate value returned by the condition // computation live as well. MarkLiveAtIndex(caller->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } else if (caller->opcode() == HloOpcode::kConditional) { // If a live instruction is within the true or false branches of a // conditional, we mark the predicate operand live as well. MarkLiveAtIndex(caller->operand(0), {}, live_index_map, worklist, workset); // Mark the caller instruction live. MarkLiveAtIndex(caller, {}, live_index_map, worklist, workset); // Propagate liveness to the caller computation. const HloComputation* callee_comp = instruction->parent(); // Initialize 'operand_index' to skip predictate operand. int64_t operand_index = 1; for (auto* caller_comp : caller->called_computations()) { if (callee_comp == caller_comp) { MarkLiveAtIndex(caller->operand(operand_index), {}, live_index_map, worklist, workset); if (instruction->opcode() == HloOpcode::kParameter) { // If 'instruction' is a parameter, propagate live shape indices // to the associated callsite's argument shape indices. const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); } break; } ++operand_index; } } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); HloLivenessAnalysis::HloLivenessAnalysis(const HloModule& module) : module_(module), call_graph_(CallGraph::Build(&module)) {} void HloLivenessAnalysis::RunAnalysis() { Worklist worklist; Workset workset; // Add entry computation root instruction. MarkLiveAtAllIndices(module_.entry_computation()->root_instruction(), &live_index_map_, &worklist, &workset); for (auto* computation : module_.computations()) { for (auto* instruction : computation->instructions()) { if (instruction->HasSideEffectNoRecurse()) { // Add instructions with side effects. MarkLiveAtAllIndices(instruction, &live_index_map_, &worklist, &workset); } } } while (!worklist.empty()) { const HloInstruction* instruction = worklist.front(); worklist.pop_front(); workset.erase(workset.find(instruction)); VLOG(1) << "VISIT instruction: " << instruction->name(); if (instruction->opcode() == HloOpcode::kTuple) { PropagateLivenessThroughTuple(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kGetTupleElement) { PropagateLivenessThroughGTE(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kWhile) { PropagateLivenessThroughWhile(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kParameter) { PropagateLivenessToParameterCallers(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } else { // Propagate liveness to called computations. for (auto* called_computation : instruction->called_computations()) { MarkLiveAtAllIndices(called_computation->root_instruction(), &live_index_map_, &worklist, &workset); } // Propagate liveness to operands. for (HloInstruction* operand : instruction->operands()) { MarkLiveAtAllIndices(operand, &live_index_map_, &worklist, &workset); } } PropagateLivenessThroughControlFlow(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } } VLOG(1) << "VISIT instruction: " << instruction->name(); bool HloLivenessAnalysis::IsLive(const HloInstruction* instruction, const ShapeIndex& shape_index) const { auto it = live_index_map_.find(instruction); return (it != live_index_map_.end()) && it->second->element(shape_index); } absl::StatusOr<std::unique_ptr<HloLivenessAnalysis>> HloLivenessAnalysis::Run( const HloModule& module) { VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString()); auto liveness_analysis = absl::WrapUnique(new HloLivenessAnalysis(module)); liveness_analysis->RunAnalysis(); return std::move(liveness_analysis); } VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString());
#include "xla/service/hlo_liveness_analysis.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class HloLivenessAnalysisTest : public HloTestBase { protected: HloLivenessAnalysisTest() {} // Run liveness analysis on the member module. For convenience returns a // reference to the generated analysis stored in analysis_. const HloLivenessAnalysis& RunLiveness(HloModule* module) { liveness_ = HloLivenessAnalysis::Run(*module).value(); return *liveness_; } HloInstruction* GetInstruction(HloModule* module, const std::string& name) { HloInstruction* to_return = nullptr; for (auto* comp : module->computations()) { for (auto* inst : comp->instructions()) { if (inst->name() == name) { to_return = inst; break; } } } return CHECK_NOTNULL(to_return); } std::unique_ptr<HloLivenessAnalysis> liveness_; }; TEST_F(HloLivenessAnalysisTest, AddAtEntryRoot) { auto module = ParseAndReturnVerifiedModule(R"( HloModule SimpleModule ENTRY SimpleComputation { constant.1 = s32[] constant(0) constant.2 = s32[] constant(1) ROOT add = s32[] add(constant.1, constant.2) })") .value(); const HloLivenessAnalysis& liveness = RunLiveness(module.get()); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "add"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.2"), {})); }
HloLivenessAnalysisTest_DeadAdd
xla/service/hlo_liveness_analysis_test.cc
void AddToWorklist(const HloInstruction* instruction, Worklist* worklist, Workset* workset) { if (workset->insert(instruction).second) { worklist->push_back(instruction); VLOG(3) << "ADD instruction: " << instruction->name(); } } VLOG(3) << "ADD instruction: " << instruction->name(); void MarkLiveAtIndex(const HloInstruction* instruction, const ShapeIndex& shape_index, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/false); } bool& alive = *liveness->mutable_element(shape_index); if (!alive) { AddToWorklist(instruction, worklist, workset); alive = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << shape_index; } } VLOG(3) << "MARK instruction: " << instruction->name() void MarkLiveAtAllIndices(const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { bool add_to_worklist = false; std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/true); add_to_worklist = true; } else { for (auto& entry : *liveness) { if (!entry.second) { add_to_worklist = true; entry.second = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << entry.first; } } } if (add_to_worklist) { AddToWorklist(instruction, worklist, workset); } } VLOG(3) << "MARK instruction: " << instruction->name() void PropagateLivenessThroughTuple( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kTuple); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughGTE( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kGetTupleElement); // Mark operand top-level index. MarkLiveAtIndex(instruction->operand(0), {}, live_index_map, worklist, workset); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); // Propagate live shape indices along GTE -> Tuple edge. ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughWhile( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kWhile); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); // Propagate liveness to while condition computation root instruction. MarkLiveAtIndex(instruction->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessToParameterCallers( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { CHECK_EQ(instruction->opcode(), HloOpcode::kParameter); const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { if (callsite.instruction()->opcode() == HloOpcode::kWhile) { auto* xla_while = callsite.instruction(); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughControlFlow( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { HloInstruction* caller = callsite.instruction(); if (caller->opcode() == HloOpcode::kWhile) { // If a live instruction is within the %while body or condition // computation, mark the predicate value returned by the condition // computation live as well. MarkLiveAtIndex(caller->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } else if (caller->opcode() == HloOpcode::kConditional) { // If a live instruction is within the true or false branches of a // conditional, we mark the predicate operand live as well. MarkLiveAtIndex(caller->operand(0), {}, live_index_map, worklist, workset); // Mark the caller instruction live. MarkLiveAtIndex(caller, {}, live_index_map, worklist, workset); // Propagate liveness to the caller computation. const HloComputation* callee_comp = instruction->parent(); // Initialize 'operand_index' to skip predictate operand. int64_t operand_index = 1; for (auto* caller_comp : caller->called_computations()) { if (callee_comp == caller_comp) { MarkLiveAtIndex(caller->operand(operand_index), {}, live_index_map, worklist, workset); if (instruction->opcode() == HloOpcode::kParameter) { // If 'instruction' is a parameter, propagate live shape indices // to the associated callsite's argument shape indices. const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); } break; } ++operand_index; } } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); HloLivenessAnalysis::HloLivenessAnalysis(const HloModule& module) : module_(module), call_graph_(CallGraph::Build(&module)) {} void HloLivenessAnalysis::RunAnalysis() { Worklist worklist; Workset workset; // Add entry computation root instruction. MarkLiveAtAllIndices(module_.entry_computation()->root_instruction(), &live_index_map_, &worklist, &workset); for (auto* computation : module_.computations()) { for (auto* instruction : computation->instructions()) { if (instruction->HasSideEffectNoRecurse()) { // Add instructions with side effects. MarkLiveAtAllIndices(instruction, &live_index_map_, &worklist, &workset); } } } while (!worklist.empty()) { const HloInstruction* instruction = worklist.front(); worklist.pop_front(); workset.erase(workset.find(instruction)); VLOG(1) << "VISIT instruction: " << instruction->name(); if (instruction->opcode() == HloOpcode::kTuple) { PropagateLivenessThroughTuple(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kGetTupleElement) { PropagateLivenessThroughGTE(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kWhile) { PropagateLivenessThroughWhile(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kParameter) { PropagateLivenessToParameterCallers(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } else { // Propagate liveness to called computations. for (auto* called_computation : instruction->called_computations()) { MarkLiveAtAllIndices(called_computation->root_instruction(), &live_index_map_, &worklist, &workset); } // Propagate liveness to operands. for (HloInstruction* operand : instruction->operands()) { MarkLiveAtAllIndices(operand, &live_index_map_, &worklist, &workset); } } PropagateLivenessThroughControlFlow(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } } VLOG(1) << "VISIT instruction: " << instruction->name(); bool HloLivenessAnalysis::IsLive(const HloInstruction* instruction, const ShapeIndex& shape_index) const { auto it = live_index_map_.find(instruction); return (it != live_index_map_.end()) && it->second->element(shape_index); } absl::StatusOr<std::unique_ptr<HloLivenessAnalysis>> HloLivenessAnalysis::Run( const HloModule& module) { VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString()); auto liveness_analysis = absl::WrapUnique(new HloLivenessAnalysis(module)); liveness_analysis->RunAnalysis(); return std::move(liveness_analysis); } VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString());
#include "xla/service/hlo_liveness_analysis.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class HloLivenessAnalysisTest : public HloTestBase { protected: HloLivenessAnalysisTest() {} // Run liveness analysis on the member module. For convenience returns a // reference to the generated analysis stored in analysis_. const HloLivenessAnalysis& RunLiveness(HloModule* module) { liveness_ = HloLivenessAnalysis::Run(*module).value(); return *liveness_; } HloInstruction* GetInstruction(HloModule* module, const std::string& name) { HloInstruction* to_return = nullptr; for (auto* comp : module->computations()) { for (auto* inst : comp->instructions()) { if (inst->name() == name) { to_return = inst; break; } } } return CHECK_NOTNULL(to_return); } std::unique_ptr<HloLivenessAnalysis> liveness_; }; TEST_F(HloLivenessAnalysisTest, DeadAdd) { auto module = ParseAndReturnVerifiedModule(R"( HloModule SimpleModule ENTRY SimpleComputation { constant.1 = s32[] constant(0) constant.2 = s32[] constant(1) add.1 = s32[] add(constant.1, constant.2) ROOT add.2 = s32[] add(constant.1, constant.2) })") .value(); const HloLivenessAnalysis& liveness = RunLiveness(module.get()); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "add.2"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.2"), {})); EXPECT_FALSE(liveness.IsLive(GetInstruction(module.get(), "add.1"), {})); }
HloLivenessAnalysisTest_GteOfGteOfNestedTuple
xla/service/hlo_liveness_analysis_test.cc
void AddToWorklist(const HloInstruction* instruction, Worklist* worklist, Workset* workset) { if (workset->insert(instruction).second) { worklist->push_back(instruction); VLOG(3) << "ADD instruction: " << instruction->name(); } } VLOG(3) << "ADD instruction: " << instruction->name(); void MarkLiveAtIndex(const HloInstruction* instruction, const ShapeIndex& shape_index, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/false); } bool& alive = *liveness->mutable_element(shape_index); if (!alive) { AddToWorklist(instruction, worklist, workset); alive = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << shape_index; } } VLOG(3) << "MARK instruction: " << instruction->name() void MarkLiveAtAllIndices(const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { bool add_to_worklist = false; std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/true); add_to_worklist = true; } else { for (auto& entry : *liveness) { if (!entry.second) { add_to_worklist = true; entry.second = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << entry.first; } } } if (add_to_worklist) { AddToWorklist(instruction, worklist, workset); } } VLOG(3) << "MARK instruction: " << instruction->name() void PropagateLivenessThroughTuple( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kTuple); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughGTE( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kGetTupleElement); // Mark operand top-level index. MarkLiveAtIndex(instruction->operand(0), {}, live_index_map, worklist, workset); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); // Propagate live shape indices along GTE -> Tuple edge. ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughWhile( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kWhile); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); // Propagate liveness to while condition computation root instruction. MarkLiveAtIndex(instruction->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessToParameterCallers( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { CHECK_EQ(instruction->opcode(), HloOpcode::kParameter); const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { if (callsite.instruction()->opcode() == HloOpcode::kWhile) { auto* xla_while = callsite.instruction(); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughControlFlow( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { HloInstruction* caller = callsite.instruction(); if (caller->opcode() == HloOpcode::kWhile) { // If a live instruction is within the %while body or condition // computation, mark the predicate value returned by the condition // computation live as well. MarkLiveAtIndex(caller->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } else if (caller->opcode() == HloOpcode::kConditional) { // If a live instruction is within the true or false branches of a // conditional, we mark the predicate operand live as well. MarkLiveAtIndex(caller->operand(0), {}, live_index_map, worklist, workset); // Mark the caller instruction live. MarkLiveAtIndex(caller, {}, live_index_map, worklist, workset); // Propagate liveness to the caller computation. const HloComputation* callee_comp = instruction->parent(); // Initialize 'operand_index' to skip predictate operand. int64_t operand_index = 1; for (auto* caller_comp : caller->called_computations()) { if (callee_comp == caller_comp) { MarkLiveAtIndex(caller->operand(operand_index), {}, live_index_map, worklist, workset); if (instruction->opcode() == HloOpcode::kParameter) { // If 'instruction' is a parameter, propagate live shape indices // to the associated callsite's argument shape indices. const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); } break; } ++operand_index; } } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); HloLivenessAnalysis::HloLivenessAnalysis(const HloModule& module) : module_(module), call_graph_(CallGraph::Build(&module)) {} void HloLivenessAnalysis::RunAnalysis() { Worklist worklist; Workset workset; // Add entry computation root instruction. MarkLiveAtAllIndices(module_.entry_computation()->root_instruction(), &live_index_map_, &worklist, &workset); for (auto* computation : module_.computations()) { for (auto* instruction : computation->instructions()) { if (instruction->HasSideEffectNoRecurse()) { // Add instructions with side effects. MarkLiveAtAllIndices(instruction, &live_index_map_, &worklist, &workset); } } } while (!worklist.empty()) { const HloInstruction* instruction = worklist.front(); worklist.pop_front(); workset.erase(workset.find(instruction)); VLOG(1) << "VISIT instruction: " << instruction->name(); if (instruction->opcode() == HloOpcode::kTuple) { PropagateLivenessThroughTuple(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kGetTupleElement) { PropagateLivenessThroughGTE(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kWhile) { PropagateLivenessThroughWhile(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kParameter) { PropagateLivenessToParameterCallers(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } else { // Propagate liveness to called computations. for (auto* called_computation : instruction->called_computations()) { MarkLiveAtAllIndices(called_computation->root_instruction(), &live_index_map_, &worklist, &workset); } // Propagate liveness to operands. for (HloInstruction* operand : instruction->operands()) { MarkLiveAtAllIndices(operand, &live_index_map_, &worklist, &workset); } } PropagateLivenessThroughControlFlow(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } } VLOG(1) << "VISIT instruction: " << instruction->name(); bool HloLivenessAnalysis::IsLive(const HloInstruction* instruction, const ShapeIndex& shape_index) const { auto it = live_index_map_.find(instruction); return (it != live_index_map_.end()) && it->second->element(shape_index); } absl::StatusOr<std::unique_ptr<HloLivenessAnalysis>> HloLivenessAnalysis::Run( const HloModule& module) { VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString()); auto liveness_analysis = absl::WrapUnique(new HloLivenessAnalysis(module)); liveness_analysis->RunAnalysis(); return std::move(liveness_analysis); } VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString());
#include "xla/service/hlo_liveness_analysis.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class HloLivenessAnalysisTest : public HloTestBase { protected: HloLivenessAnalysisTest() {} // Run liveness analysis on the member module. For convenience returns a // reference to the generated analysis stored in analysis_. const HloLivenessAnalysis& RunLiveness(HloModule* module) { liveness_ = HloLivenessAnalysis::Run(*module).value(); return *liveness_; } HloInstruction* GetInstruction(HloModule* module, const std::string& name) { HloInstruction* to_return = nullptr; for (auto* comp : module->computations()) { for (auto* inst : comp->instructions()) { if (inst->name() == name) { to_return = inst; break; } } } return CHECK_NOTNULL(to_return); } std::unique_ptr<HloLivenessAnalysis> liveness_; }; TEST_F(HloLivenessAnalysisTest, GteOfGteOfNestedTuple) { auto module = ParseAndReturnVerifiedModule(R"( HloModule SimpleModule ENTRY SimpleComputation { constant.1 = s32[] constant(0) constant.2 = s32[] constant(1) constant.3 = s32[] constant(2) tuple.1 = (s32[], s32[]) tuple(constant.2, constant.3) tuple.2 = (s32[], (s32[], s32[])) tuple(constant.1, tuple.1) get-tuple-element.1 = (s32[], s32[]) get-tuple-element(tuple.2), index=1 ROOT get-tuple-element.2 = s32[] get-tuple-element(get-tuple-element.1), index=0 })") .value(); const HloLivenessAnalysis& liveness = RunLiveness(module.get()); EXPECT_TRUE( liveness.IsLive(GetInstruction(module.get(), "get-tuple-element.2"), {})); EXPECT_TRUE( liveness.IsLive(GetInstruction(module.get(), "get-tuple-element.1"), {})); EXPECT_TRUE(liveness.IsLive( GetInstruction(module.get(), "get-tuple-element.1"), {0})); EXPECT_FALSE(liveness.IsLive( GetInstruction(module.get(), "get-tuple-element.1"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {})); EXPECT_FALSE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {1, 0})); EXPECT_FALSE( liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {1, 1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {0})); EXPECT_FALSE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {1})); EXPECT_FALSE(liveness.IsLive(GetInstruction(module.get(), "constant.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.2"), {})); EXPECT_FALSE(liveness.IsLive(GetInstruction(module.get(), "constant.3"), {})); }
HloLivenessAnalysisTest_GteOfNestedTuple
xla/service/hlo_liveness_analysis_test.cc
void AddToWorklist(const HloInstruction* instruction, Worklist* worklist, Workset* workset) { if (workset->insert(instruction).second) { worklist->push_back(instruction); VLOG(3) << "ADD instruction: " << instruction->name(); } } VLOG(3) << "ADD instruction: " << instruction->name(); void MarkLiveAtIndex(const HloInstruction* instruction, const ShapeIndex& shape_index, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/false); } bool& alive = *liveness->mutable_element(shape_index); if (!alive) { AddToWorklist(instruction, worklist, workset); alive = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << shape_index; } } VLOG(3) << "MARK instruction: " << instruction->name() void MarkLiveAtAllIndices(const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { bool add_to_worklist = false; std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/true); add_to_worklist = true; } else { for (auto& entry : *liveness) { if (!entry.second) { add_to_worklist = true; entry.second = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << entry.first; } } } if (add_to_worklist) { AddToWorklist(instruction, worklist, workset); } } VLOG(3) << "MARK instruction: " << instruction->name() void PropagateLivenessThroughTuple( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kTuple); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughGTE( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kGetTupleElement); // Mark operand top-level index. MarkLiveAtIndex(instruction->operand(0), {}, live_index_map, worklist, workset); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); // Propagate live shape indices along GTE -> Tuple edge. ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughWhile( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kWhile); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); // Propagate liveness to while condition computation root instruction. MarkLiveAtIndex(instruction->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessToParameterCallers( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { CHECK_EQ(instruction->opcode(), HloOpcode::kParameter); const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { if (callsite.instruction()->opcode() == HloOpcode::kWhile) { auto* xla_while = callsite.instruction(); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughControlFlow( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { HloInstruction* caller = callsite.instruction(); if (caller->opcode() == HloOpcode::kWhile) { // If a live instruction is within the %while body or condition // computation, mark the predicate value returned by the condition // computation live as well. MarkLiveAtIndex(caller->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } else if (caller->opcode() == HloOpcode::kConditional) { // If a live instruction is within the true or false branches of a // conditional, we mark the predicate operand live as well. MarkLiveAtIndex(caller->operand(0), {}, live_index_map, worklist, workset); // Mark the caller instruction live. MarkLiveAtIndex(caller, {}, live_index_map, worklist, workset); // Propagate liveness to the caller computation. const HloComputation* callee_comp = instruction->parent(); // Initialize 'operand_index' to skip predictate operand. int64_t operand_index = 1; for (auto* caller_comp : caller->called_computations()) { if (callee_comp == caller_comp) { MarkLiveAtIndex(caller->operand(operand_index), {}, live_index_map, worklist, workset); if (instruction->opcode() == HloOpcode::kParameter) { // If 'instruction' is a parameter, propagate live shape indices // to the associated callsite's argument shape indices. const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); } break; } ++operand_index; } } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); HloLivenessAnalysis::HloLivenessAnalysis(const HloModule& module) : module_(module), call_graph_(CallGraph::Build(&module)) {} void HloLivenessAnalysis::RunAnalysis() { Worklist worklist; Workset workset; // Add entry computation root instruction. MarkLiveAtAllIndices(module_.entry_computation()->root_instruction(), &live_index_map_, &worklist, &workset); for (auto* computation : module_.computations()) { for (auto* instruction : computation->instructions()) { if (instruction->HasSideEffectNoRecurse()) { // Add instructions with side effects. MarkLiveAtAllIndices(instruction, &live_index_map_, &worklist, &workset); } } } while (!worklist.empty()) { const HloInstruction* instruction = worklist.front(); worklist.pop_front(); workset.erase(workset.find(instruction)); VLOG(1) << "VISIT instruction: " << instruction->name(); if (instruction->opcode() == HloOpcode::kTuple) { PropagateLivenessThroughTuple(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kGetTupleElement) { PropagateLivenessThroughGTE(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kWhile) { PropagateLivenessThroughWhile(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kParameter) { PropagateLivenessToParameterCallers(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } else { // Propagate liveness to called computations. for (auto* called_computation : instruction->called_computations()) { MarkLiveAtAllIndices(called_computation->root_instruction(), &live_index_map_, &worklist, &workset); } // Propagate liveness to operands. for (HloInstruction* operand : instruction->operands()) { MarkLiveAtAllIndices(operand, &live_index_map_, &worklist, &workset); } } PropagateLivenessThroughControlFlow(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } } VLOG(1) << "VISIT instruction: " << instruction->name(); bool HloLivenessAnalysis::IsLive(const HloInstruction* instruction, const ShapeIndex& shape_index) const { auto it = live_index_map_.find(instruction); return (it != live_index_map_.end()) && it->second->element(shape_index); } absl::StatusOr<std::unique_ptr<HloLivenessAnalysis>> HloLivenessAnalysis::Run( const HloModule& module) { VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString()); auto liveness_analysis = absl::WrapUnique(new HloLivenessAnalysis(module)); liveness_analysis->RunAnalysis(); return std::move(liveness_analysis); } VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString());
#include "xla/service/hlo_liveness_analysis.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class HloLivenessAnalysisTest : public HloTestBase { protected: HloLivenessAnalysisTest() {} // Run liveness analysis on the member module. For convenience returns a // reference to the generated analysis stored in analysis_. const HloLivenessAnalysis& RunLiveness(HloModule* module) { liveness_ = HloLivenessAnalysis::Run(*module).value(); return *liveness_; } HloInstruction* GetInstruction(HloModule* module, const std::string& name) { HloInstruction* to_return = nullptr; for (auto* comp : module->computations()) { for (auto* inst : comp->instructions()) { if (inst->name() == name) { to_return = inst; break; } } } return CHECK_NOTNULL(to_return); } std::unique_ptr<HloLivenessAnalysis> liveness_; }; TEST_F(HloLivenessAnalysisTest, GteOfNestedTuple) { auto module = ParseAndReturnVerifiedModule(R"( HloModule SimpleModule ENTRY SimpleComputation { constant.1 = s32[] constant(0) constant.2 = s32[] constant(1) constant.3 = s32[] constant(2) tuple.1 = (s32[], s32[]) tuple(constant.2, constant.3) tuple.2 = (s32[], (s32[], s32[])) tuple(constant.1, tuple.1) ROOT get-tuple-element.1 = (s32[], s32[]) get-tuple-element(tuple.2), index=1 })") .value(); const HloLivenessAnalysis& liveness = RunLiveness(module.get()); EXPECT_TRUE( liveness.IsLive(GetInstruction(module.get(), "get-tuple-element.1"), {})); EXPECT_TRUE(liveness.IsLive( GetInstruction(module.get(), "get-tuple-element.1"), {0})); EXPECT_TRUE(liveness.IsLive( GetInstruction(module.get(), "get-tuple-element.1"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {})); EXPECT_FALSE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {1, 0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {1, 1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {1})); EXPECT_FALSE(liveness.IsLive(GetInstruction(module.get(), "constant.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.2"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.3"), {})); }
HloLivenessAnalysisTest_GteOfTuple
xla/service/hlo_liveness_analysis_test.cc
void AddToWorklist(const HloInstruction* instruction, Worklist* worklist, Workset* workset) { if (workset->insert(instruction).second) { worklist->push_back(instruction); VLOG(3) << "ADD instruction: " << instruction->name(); } } VLOG(3) << "ADD instruction: " << instruction->name(); void MarkLiveAtIndex(const HloInstruction* instruction, const ShapeIndex& shape_index, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/false); } bool& alive = *liveness->mutable_element(shape_index); if (!alive) { AddToWorklist(instruction, worklist, workset); alive = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << shape_index; } } VLOG(3) << "MARK instruction: " << instruction->name() void MarkLiveAtAllIndices(const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { bool add_to_worklist = false; std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/true); add_to_worklist = true; } else { for (auto& entry : *liveness) { if (!entry.second) { add_to_worklist = true; entry.second = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << entry.first; } } } if (add_to_worklist) { AddToWorklist(instruction, worklist, workset); } } VLOG(3) << "MARK instruction: " << instruction->name() void PropagateLivenessThroughTuple( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kTuple); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughGTE( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kGetTupleElement); // Mark operand top-level index. MarkLiveAtIndex(instruction->operand(0), {}, live_index_map, worklist, workset); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); // Propagate live shape indices along GTE -> Tuple edge. ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughWhile( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kWhile); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); // Propagate liveness to while condition computation root instruction. MarkLiveAtIndex(instruction->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessToParameterCallers( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { CHECK_EQ(instruction->opcode(), HloOpcode::kParameter); const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { if (callsite.instruction()->opcode() == HloOpcode::kWhile) { auto* xla_while = callsite.instruction(); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughControlFlow( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { HloInstruction* caller = callsite.instruction(); if (caller->opcode() == HloOpcode::kWhile) { // If a live instruction is within the %while body or condition // computation, mark the predicate value returned by the condition // computation live as well. MarkLiveAtIndex(caller->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } else if (caller->opcode() == HloOpcode::kConditional) { // If a live instruction is within the true or false branches of a // conditional, we mark the predicate operand live as well. MarkLiveAtIndex(caller->operand(0), {}, live_index_map, worklist, workset); // Mark the caller instruction live. MarkLiveAtIndex(caller, {}, live_index_map, worklist, workset); // Propagate liveness to the caller computation. const HloComputation* callee_comp = instruction->parent(); // Initialize 'operand_index' to skip predictate operand. int64_t operand_index = 1; for (auto* caller_comp : caller->called_computations()) { if (callee_comp == caller_comp) { MarkLiveAtIndex(caller->operand(operand_index), {}, live_index_map, worklist, workset); if (instruction->opcode() == HloOpcode::kParameter) { // If 'instruction' is a parameter, propagate live shape indices // to the associated callsite's argument shape indices. const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); } break; } ++operand_index; } } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); HloLivenessAnalysis::HloLivenessAnalysis(const HloModule& module) : module_(module), call_graph_(CallGraph::Build(&module)) {} void HloLivenessAnalysis::RunAnalysis() { Worklist worklist; Workset workset; // Add entry computation root instruction. MarkLiveAtAllIndices(module_.entry_computation()->root_instruction(), &live_index_map_, &worklist, &workset); for (auto* computation : module_.computations()) { for (auto* instruction : computation->instructions()) { if (instruction->HasSideEffectNoRecurse()) { // Add instructions with side effects. MarkLiveAtAllIndices(instruction, &live_index_map_, &worklist, &workset); } } } while (!worklist.empty()) { const HloInstruction* instruction = worklist.front(); worklist.pop_front(); workset.erase(workset.find(instruction)); VLOG(1) << "VISIT instruction: " << instruction->name(); if (instruction->opcode() == HloOpcode::kTuple) { PropagateLivenessThroughTuple(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kGetTupleElement) { PropagateLivenessThroughGTE(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kWhile) { PropagateLivenessThroughWhile(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kParameter) { PropagateLivenessToParameterCallers(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } else { // Propagate liveness to called computations. for (auto* called_computation : instruction->called_computations()) { MarkLiveAtAllIndices(called_computation->root_instruction(), &live_index_map_, &worklist, &workset); } // Propagate liveness to operands. for (HloInstruction* operand : instruction->operands()) { MarkLiveAtAllIndices(operand, &live_index_map_, &worklist, &workset); } } PropagateLivenessThroughControlFlow(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } } VLOG(1) << "VISIT instruction: " << instruction->name(); bool HloLivenessAnalysis::IsLive(const HloInstruction* instruction, const ShapeIndex& shape_index) const { auto it = live_index_map_.find(instruction); return (it != live_index_map_.end()) && it->second->element(shape_index); } absl::StatusOr<std::unique_ptr<HloLivenessAnalysis>> HloLivenessAnalysis::Run( const HloModule& module) { VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString()); auto liveness_analysis = absl::WrapUnique(new HloLivenessAnalysis(module)); liveness_analysis->RunAnalysis(); return std::move(liveness_analysis); } VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString());
#include "xla/service/hlo_liveness_analysis.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class HloLivenessAnalysisTest : public HloTestBase { protected: HloLivenessAnalysisTest() {} // Run liveness analysis on the member module. For convenience returns a // reference to the generated analysis stored in analysis_. const HloLivenessAnalysis& RunLiveness(HloModule* module) { liveness_ = HloLivenessAnalysis::Run(*module).value(); return *liveness_; } HloInstruction* GetInstruction(HloModule* module, const std::string& name) { HloInstruction* to_return = nullptr; for (auto* comp : module->computations()) { for (auto* inst : comp->instructions()) { if (inst->name() == name) { to_return = inst; break; } } } return CHECK_NOTNULL(to_return); } std::unique_ptr<HloLivenessAnalysis> liveness_; }; TEST_F(HloLivenessAnalysisTest, GteOfTuple) { auto module = ParseAndReturnVerifiedModule(R"( HloModule SimpleModule ENTRY SimpleComputation { constant.1 = s32[] constant(0) constant.2 = s32[] constant(1) tuple.1 = (s32[], s32[]) tuple(constant.1, constant.2) ROOT get-tuple-element.1 = s32[] get-tuple-element(tuple.1), index=0 })") .value(); const HloLivenessAnalysis& liveness = RunLiveness(module.get()); EXPECT_TRUE( liveness.IsLive(GetInstruction(module.get(), "get-tuple-element.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {0})); EXPECT_FALSE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.1"), {})); EXPECT_FALSE(liveness.IsLive(GetInstruction(module.get(), "constant.2"), {})); }
HloLivenessAnalysisTest_NestedTupleAtEntryRoot
xla/service/hlo_liveness_analysis_test.cc
void AddToWorklist(const HloInstruction* instruction, Worklist* worklist, Workset* workset) { if (workset->insert(instruction).second) { worklist->push_back(instruction); VLOG(3) << "ADD instruction: " << instruction->name(); } } VLOG(3) << "ADD instruction: " << instruction->name(); void MarkLiveAtIndex(const HloInstruction* instruction, const ShapeIndex& shape_index, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/false); } bool& alive = *liveness->mutable_element(shape_index); if (!alive) { AddToWorklist(instruction, worklist, workset); alive = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << shape_index; } } VLOG(3) << "MARK instruction: " << instruction->name() void MarkLiveAtAllIndices(const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { bool add_to_worklist = false; std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/true); add_to_worklist = true; } else { for (auto& entry : *liveness) { if (!entry.second) { add_to_worklist = true; entry.second = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << entry.first; } } } if (add_to_worklist) { AddToWorklist(instruction, worklist, workset); } } VLOG(3) << "MARK instruction: " << instruction->name() void PropagateLivenessThroughTuple( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kTuple); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughGTE( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kGetTupleElement); // Mark operand top-level index. MarkLiveAtIndex(instruction->operand(0), {}, live_index_map, worklist, workset); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); // Propagate live shape indices along GTE -> Tuple edge. ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughWhile( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kWhile); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); // Propagate liveness to while condition computation root instruction. MarkLiveAtIndex(instruction->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessToParameterCallers( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { CHECK_EQ(instruction->opcode(), HloOpcode::kParameter); const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { if (callsite.instruction()->opcode() == HloOpcode::kWhile) { auto* xla_while = callsite.instruction(); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughControlFlow( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { HloInstruction* caller = callsite.instruction(); if (caller->opcode() == HloOpcode::kWhile) { // If a live instruction is within the %while body or condition // computation, mark the predicate value returned by the condition // computation live as well. MarkLiveAtIndex(caller->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } else if (caller->opcode() == HloOpcode::kConditional) { // If a live instruction is within the true or false branches of a // conditional, we mark the predicate operand live as well. MarkLiveAtIndex(caller->operand(0), {}, live_index_map, worklist, workset); // Mark the caller instruction live. MarkLiveAtIndex(caller, {}, live_index_map, worklist, workset); // Propagate liveness to the caller computation. const HloComputation* callee_comp = instruction->parent(); // Initialize 'operand_index' to skip predictate operand. int64_t operand_index = 1; for (auto* caller_comp : caller->called_computations()) { if (callee_comp == caller_comp) { MarkLiveAtIndex(caller->operand(operand_index), {}, live_index_map, worklist, workset); if (instruction->opcode() == HloOpcode::kParameter) { // If 'instruction' is a parameter, propagate live shape indices // to the associated callsite's argument shape indices. const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); } break; } ++operand_index; } } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); HloLivenessAnalysis::HloLivenessAnalysis(const HloModule& module) : module_(module), call_graph_(CallGraph::Build(&module)) {} void HloLivenessAnalysis::RunAnalysis() { Worklist worklist; Workset workset; // Add entry computation root instruction. MarkLiveAtAllIndices(module_.entry_computation()->root_instruction(), &live_index_map_, &worklist, &workset); for (auto* computation : module_.computations()) { for (auto* instruction : computation->instructions()) { if (instruction->HasSideEffectNoRecurse()) { // Add instructions with side effects. MarkLiveAtAllIndices(instruction, &live_index_map_, &worklist, &workset); } } } while (!worklist.empty()) { const HloInstruction* instruction = worklist.front(); worklist.pop_front(); workset.erase(workset.find(instruction)); VLOG(1) << "VISIT instruction: " << instruction->name(); if (instruction->opcode() == HloOpcode::kTuple) { PropagateLivenessThroughTuple(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kGetTupleElement) { PropagateLivenessThroughGTE(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kWhile) { PropagateLivenessThroughWhile(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kParameter) { PropagateLivenessToParameterCallers(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } else { // Propagate liveness to called computations. for (auto* called_computation : instruction->called_computations()) { MarkLiveAtAllIndices(called_computation->root_instruction(), &live_index_map_, &worklist, &workset); } // Propagate liveness to operands. for (HloInstruction* operand : instruction->operands()) { MarkLiveAtAllIndices(operand, &live_index_map_, &worklist, &workset); } } PropagateLivenessThroughControlFlow(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } } VLOG(1) << "VISIT instruction: " << instruction->name(); bool HloLivenessAnalysis::IsLive(const HloInstruction* instruction, const ShapeIndex& shape_index) const { auto it = live_index_map_.find(instruction); return (it != live_index_map_.end()) && it->second->element(shape_index); } absl::StatusOr<std::unique_ptr<HloLivenessAnalysis>> HloLivenessAnalysis::Run( const HloModule& module) { VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString()); auto liveness_analysis = absl::WrapUnique(new HloLivenessAnalysis(module)); liveness_analysis->RunAnalysis(); return std::move(liveness_analysis); } VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString());
#include "xla/service/hlo_liveness_analysis.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class HloLivenessAnalysisTest : public HloTestBase { protected: HloLivenessAnalysisTest() {} // Run liveness analysis on the member module. For convenience returns a // reference to the generated analysis stored in analysis_. const HloLivenessAnalysis& RunLiveness(HloModule* module) { liveness_ = HloLivenessAnalysis::Run(*module).value(); return *liveness_; } HloInstruction* GetInstruction(HloModule* module, const std::string& name) { HloInstruction* to_return = nullptr; for (auto* comp : module->computations()) { for (auto* inst : comp->instructions()) { if (inst->name() == name) { to_return = inst; break; } } } return CHECK_NOTNULL(to_return); } std::unique_ptr<HloLivenessAnalysis> liveness_; }; TEST_F(HloLivenessAnalysisTest, NestedTupleAtEntryRoot) { auto module = ParseAndReturnVerifiedModule(R"( HloModule SimpleModule ENTRY SimpleComputation { constant.1 = s32[] constant(1) constant.2 = s32[] constant(2) constant.3 = s32[] constant(3) tuple.1 = (s32[], s32[]) tuple(constant.2, constant.3) ROOT tuple.2 = (s32[], (s32[], s32[])) tuple(constant.1, tuple.1) })") .value(); const HloLivenessAnalysis& liveness = RunLiveness(module.get()); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {1, 0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {1, 1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.2"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.3"), {})); }
HloLivenessAnalysisTest_NestedWhileWithOutfeed
xla/service/hlo_liveness_analysis_test.cc
void AddToWorklist(const HloInstruction* instruction, Worklist* worklist, Workset* workset) { if (workset->insert(instruction).second) { worklist->push_back(instruction); VLOG(3) << "ADD instruction: " << instruction->name(); } } VLOG(3) << "ADD instruction: " << instruction->name(); void MarkLiveAtIndex(const HloInstruction* instruction, const ShapeIndex& shape_index, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/false); } bool& alive = *liveness->mutable_element(shape_index); if (!alive) { AddToWorklist(instruction, worklist, workset); alive = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << shape_index; } } VLOG(3) << "MARK instruction: " << instruction->name() void MarkLiveAtAllIndices(const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { bool add_to_worklist = false; std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/true); add_to_worklist = true; } else { for (auto& entry : *liveness) { if (!entry.second) { add_to_worklist = true; entry.second = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << entry.first; } } } if (add_to_worklist) { AddToWorklist(instruction, worklist, workset); } } VLOG(3) << "MARK instruction: " << instruction->name() void PropagateLivenessThroughTuple( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kTuple); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughGTE( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kGetTupleElement); // Mark operand top-level index. MarkLiveAtIndex(instruction->operand(0), {}, live_index_map, worklist, workset); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); // Propagate live shape indices along GTE -> Tuple edge. ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughWhile( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kWhile); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); // Propagate liveness to while condition computation root instruction. MarkLiveAtIndex(instruction->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessToParameterCallers( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { CHECK_EQ(instruction->opcode(), HloOpcode::kParameter); const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { if (callsite.instruction()->opcode() == HloOpcode::kWhile) { auto* xla_while = callsite.instruction(); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughControlFlow( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { HloInstruction* caller = callsite.instruction(); if (caller->opcode() == HloOpcode::kWhile) { // If a live instruction is within the %while body or condition // computation, mark the predicate value returned by the condition // computation live as well. MarkLiveAtIndex(caller->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } else if (caller->opcode() == HloOpcode::kConditional) { // If a live instruction is within the true or false branches of a // conditional, we mark the predicate operand live as well. MarkLiveAtIndex(caller->operand(0), {}, live_index_map, worklist, workset); // Mark the caller instruction live. MarkLiveAtIndex(caller, {}, live_index_map, worklist, workset); // Propagate liveness to the caller computation. const HloComputation* callee_comp = instruction->parent(); // Initialize 'operand_index' to skip predictate operand. int64_t operand_index = 1; for (auto* caller_comp : caller->called_computations()) { if (callee_comp == caller_comp) { MarkLiveAtIndex(caller->operand(operand_index), {}, live_index_map, worklist, workset); if (instruction->opcode() == HloOpcode::kParameter) { // If 'instruction' is a parameter, propagate live shape indices // to the associated callsite's argument shape indices. const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); } break; } ++operand_index; } } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); HloLivenessAnalysis::HloLivenessAnalysis(const HloModule& module) : module_(module), call_graph_(CallGraph::Build(&module)) {} void HloLivenessAnalysis::RunAnalysis() { Worklist worklist; Workset workset; // Add entry computation root instruction. MarkLiveAtAllIndices(module_.entry_computation()->root_instruction(), &live_index_map_, &worklist, &workset); for (auto* computation : module_.computations()) { for (auto* instruction : computation->instructions()) { if (instruction->HasSideEffectNoRecurse()) { // Add instructions with side effects. MarkLiveAtAllIndices(instruction, &live_index_map_, &worklist, &workset); } } } while (!worklist.empty()) { const HloInstruction* instruction = worklist.front(); worklist.pop_front(); workset.erase(workset.find(instruction)); VLOG(1) << "VISIT instruction: " << instruction->name(); if (instruction->opcode() == HloOpcode::kTuple) { PropagateLivenessThroughTuple(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kGetTupleElement) { PropagateLivenessThroughGTE(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kWhile) { PropagateLivenessThroughWhile(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kParameter) { PropagateLivenessToParameterCallers(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } else { // Propagate liveness to called computations. for (auto* called_computation : instruction->called_computations()) { MarkLiveAtAllIndices(called_computation->root_instruction(), &live_index_map_, &worklist, &workset); } // Propagate liveness to operands. for (HloInstruction* operand : instruction->operands()) { MarkLiveAtAllIndices(operand, &live_index_map_, &worklist, &workset); } } PropagateLivenessThroughControlFlow(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } } VLOG(1) << "VISIT instruction: " << instruction->name(); bool HloLivenessAnalysis::IsLive(const HloInstruction* instruction, const ShapeIndex& shape_index) const { auto it = live_index_map_.find(instruction); return (it != live_index_map_.end()) && it->second->element(shape_index); } absl::StatusOr<std::unique_ptr<HloLivenessAnalysis>> HloLivenessAnalysis::Run( const HloModule& module) { VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString()); auto liveness_analysis = absl::WrapUnique(new HloLivenessAnalysis(module)); liveness_analysis->RunAnalysis(); return std::move(liveness_analysis); } VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString());
#include "xla/service/hlo_liveness_analysis.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class HloLivenessAnalysisTest : public HloTestBase { protected: HloLivenessAnalysisTest() {} // Run liveness analysis on the member module. For convenience returns a // reference to the generated analysis stored in analysis_. const HloLivenessAnalysis& RunLiveness(HloModule* module) { liveness_ = HloLivenessAnalysis::Run(*module).value(); return *liveness_; } HloInstruction* GetInstruction(HloModule* module, const std::string& name) { HloInstruction* to_return = nullptr; for (auto* comp : module->computations()) { for (auto* inst : comp->instructions()) { if (inst->name() == name) { to_return = inst; break; } } } return CHECK_NOTNULL(to_return); } std::unique_ptr<HloLivenessAnalysis> liveness_; }; TEST_F(HloLivenessAnalysisTest, NestedWhileWithOutfeed) { auto module = ParseAndReturnVerifiedModule(R"( HloModule OutfeedLoop InnerWhileBody { body_param = (s32[]) parameter(0) token0 = token[] after-all() constant.2 = s32[] constant(2) outfeed_tuple = (s32[]) outfeed(constant.2, token0) get-tuple-element.1 = s32[] get-tuple-element(body_param), index=0 constant.1 = s32[] constant(1) add = s32[] add(get-tuple-element.1, constant.1) ROOT tuple = (s32[]) tuple(add) } InnerWhileCondition { cond_param = (s32[]) parameter(0) get-tuple-element.3 = s32[] get-tuple-element(cond_param), index=0 constant.2 = s32[] constant(10) ROOT less-than = pred[] compare(get-tuple-element.3, constant.2), direction=LT } OuterWhileCondition { cond_param.2 = (s32[]) parameter(0) get-tuple-element.5 = s32[] get-tuple-element(cond_param.2), index=0 constant.5 = s32[] constant(5) ROOT less-than.2 = pred[] compare(get-tuple-element.5, constant.5), direction=LT } OuterWhileBody { body_param.2 = (s32[]) parameter(0) get-tuple-element.8 = s32[] get-tuple-element(body_param.2), index=0 constant.6 = s32[] constant(0) tuple.2 = (s32[]) tuple(constant.6) inner_while = (s32[]) while(tuple.2), condition=InnerWhileCondition, body=InnerWhileBody constant.7 = s32[] constant(1) add.2 = s32[] add(get-tuple-element.8, constant.7) ROOT rtuple = (s32[]) tuple(add.2) } ENTRY SimpleLoop { constant.3 = s32[] constant(0) tuple.1 = (s32[]) tuple(constant.3) while = (s32[]) while(tuple.1), condition=OuterWhileCondition, body=OuterWhileBody ROOT rtuple = () tuple() })") .value(); const HloLivenessAnalysis& liveness = RunLiveness(module.get()); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "add"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "add.2"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.3"), {})); }
HloLivenessAnalysisTest_PropagateLivenessFromConditionalComputation
xla/service/hlo_liveness_analysis_test.cc
void AddToWorklist(const HloInstruction* instruction, Worklist* worklist, Workset* workset) { if (workset->insert(instruction).second) { worklist->push_back(instruction); VLOG(3) << "ADD instruction: " << instruction->name(); } } VLOG(3) << "ADD instruction: " << instruction->name(); void MarkLiveAtIndex(const HloInstruction* instruction, const ShapeIndex& shape_index, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/false); } bool& alive = *liveness->mutable_element(shape_index); if (!alive) { AddToWorklist(instruction, worklist, workset); alive = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << shape_index; } } VLOG(3) << "MARK instruction: " << instruction->name() void MarkLiveAtAllIndices(const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { bool add_to_worklist = false; std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/true); add_to_worklist = true; } else { for (auto& entry : *liveness) { if (!entry.second) { add_to_worklist = true; entry.second = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << entry.first; } } } if (add_to_worklist) { AddToWorklist(instruction, worklist, workset); } } VLOG(3) << "MARK instruction: " << instruction->name() void PropagateLivenessThroughTuple( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kTuple); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughGTE( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kGetTupleElement); // Mark operand top-level index. MarkLiveAtIndex(instruction->operand(0), {}, live_index_map, worklist, workset); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); // Propagate live shape indices along GTE -> Tuple edge. ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughWhile( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kWhile); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); // Propagate liveness to while condition computation root instruction. MarkLiveAtIndex(instruction->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessToParameterCallers( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { CHECK_EQ(instruction->opcode(), HloOpcode::kParameter); const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { if (callsite.instruction()->opcode() == HloOpcode::kWhile) { auto* xla_while = callsite.instruction(); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughControlFlow( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { HloInstruction* caller = callsite.instruction(); if (caller->opcode() == HloOpcode::kWhile) { // If a live instruction is within the %while body or condition // computation, mark the predicate value returned by the condition // computation live as well. MarkLiveAtIndex(caller->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } else if (caller->opcode() == HloOpcode::kConditional) { // If a live instruction is within the true or false branches of a // conditional, we mark the predicate operand live as well. MarkLiveAtIndex(caller->operand(0), {}, live_index_map, worklist, workset); // Mark the caller instruction live. MarkLiveAtIndex(caller, {}, live_index_map, worklist, workset); // Propagate liveness to the caller computation. const HloComputation* callee_comp = instruction->parent(); // Initialize 'operand_index' to skip predictate operand. int64_t operand_index = 1; for (auto* caller_comp : caller->called_computations()) { if (callee_comp == caller_comp) { MarkLiveAtIndex(caller->operand(operand_index), {}, live_index_map, worklist, workset); if (instruction->opcode() == HloOpcode::kParameter) { // If 'instruction' is a parameter, propagate live shape indices // to the associated callsite's argument shape indices. const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); } break; } ++operand_index; } } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); HloLivenessAnalysis::HloLivenessAnalysis(const HloModule& module) : module_(module), call_graph_(CallGraph::Build(&module)) {} void HloLivenessAnalysis::RunAnalysis() { Worklist worklist; Workset workset; // Add entry computation root instruction. MarkLiveAtAllIndices(module_.entry_computation()->root_instruction(), &live_index_map_, &worklist, &workset); for (auto* computation : module_.computations()) { for (auto* instruction : computation->instructions()) { if (instruction->HasSideEffectNoRecurse()) { // Add instructions with side effects. MarkLiveAtAllIndices(instruction, &live_index_map_, &worklist, &workset); } } } while (!worklist.empty()) { const HloInstruction* instruction = worklist.front(); worklist.pop_front(); workset.erase(workset.find(instruction)); VLOG(1) << "VISIT instruction: " << instruction->name(); if (instruction->opcode() == HloOpcode::kTuple) { PropagateLivenessThroughTuple(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kGetTupleElement) { PropagateLivenessThroughGTE(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kWhile) { PropagateLivenessThroughWhile(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kParameter) { PropagateLivenessToParameterCallers(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } else { // Propagate liveness to called computations. for (auto* called_computation : instruction->called_computations()) { MarkLiveAtAllIndices(called_computation->root_instruction(), &live_index_map_, &worklist, &workset); } // Propagate liveness to operands. for (HloInstruction* operand : instruction->operands()) { MarkLiveAtAllIndices(operand, &live_index_map_, &worklist, &workset); } } PropagateLivenessThroughControlFlow(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } } VLOG(1) << "VISIT instruction: " << instruction->name(); bool HloLivenessAnalysis::IsLive(const HloInstruction* instruction, const ShapeIndex& shape_index) const { auto it = live_index_map_.find(instruction); return (it != live_index_map_.end()) && it->second->element(shape_index); } absl::StatusOr<std::unique_ptr<HloLivenessAnalysis>> HloLivenessAnalysis::Run( const HloModule& module) { VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString()); auto liveness_analysis = absl::WrapUnique(new HloLivenessAnalysis(module)); liveness_analysis->RunAnalysis(); return std::move(liveness_analysis); } VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString());
#include "xla/service/hlo_liveness_analysis.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class HloLivenessAnalysisTest : public HloTestBase { protected: HloLivenessAnalysisTest() {} // Run liveness analysis on the member module. For convenience returns a // reference to the generated analysis stored in analysis_. const HloLivenessAnalysis& RunLiveness(HloModule* module) { liveness_ = HloLivenessAnalysis::Run(*module).value(); return *liveness_; } HloInstruction* GetInstruction(HloModule* module, const std::string& name) { HloInstruction* to_return = nullptr; for (auto* comp : module->computations()) { for (auto* inst : comp->instructions()) { if (inst->name() == name) { to_return = inst; break; } } } return CHECK_NOTNULL(to_return); } std::unique_ptr<HloLivenessAnalysis> liveness_; }; TEST_F(HloLivenessAnalysisTest, PropagateLivenessFromConditionalComputation) { auto module = ParseAndReturnVerifiedModule(R"( HloModule main.67 %region_0.10 (Arg_0.11: (s32[], s32[], f32[1024,3], s32[1])) -> (s32[], s32[], f32[1024,3], s32[1]) { %Arg_0.11 = (s32[], s32[], f32[1024,3]{1,0}, s32[1]{0}) parameter(0) %get-tuple-element.17 = s32[] get-tuple-element((s32[], s32[], f32[1024,3]{1,0}, s32[1]{0}) %Arg_0.11), index=0, metadata={op_name="while"} %constant.13 = s32[] constant(1) %add.25 = s32[] add(s32[] %get-tuple-element.17, s32[] %constant.13), metadata={op_name="while/add_1"} %get-tuple-element.18 = s32[] get-tuple-element((s32[], s32[], f32[1024,3]{1,0}, s32[1]{0}) %Arg_0.11), index=1, metadata={op_name="while"} %add.22 = s32[] add(s32[] %get-tuple-element.18, s32[] %constant.13), metadata={op_name="while/add"} %get-tuple-element.19 = f32[1024,3]{1,0} get-tuple-element((s32[], s32[], f32[1024,3]{1,0}, s32[1]{0}) %Arg_0.11), index=2, metadata={op_name="while"} %constant.16 = f32[] constant(0) %constant.15 = f32[] constant(1) %rng.21 = f32[3]{0} rng(f32[] %constant.16, f32[] %constant.15), distribution=rng_uniform, metadata={op_name="while/random_uniform/RandomUniform"} %reshape.23 = f32[1,3]{1,0} reshape(f32[3]{0} %rng.21), metadata={op_name="while/TensorArrayV2Write/TensorListSetItem"} %constant.12 = s32[] constant(0) %dynamic-update-slice.24 = f32[1024,3]{1,0} dynamic-update-slice(f32[1024,3]{1,0} %get-tuple-element.19, f32[1,3]{1,0} %reshape.23, s32[] %get-tuple-element.18, s32[] %constant.12), metadata={op_name="while/TensorArrayV2Write/TensorListSetItem"} %get-tuple-element.20 = s32[1]{0} get-tuple-element((s32[], s32[], f32[1024,3]{1,0}, s32[1]{0}) %Arg_0.11), index=3, metadata={op_name="while"} ROOT %tuple.26 = (s32[], s32[], f32[1024,3]{1,0}, s32[1]{0}) tuple(s32[] %add.25, s32[] %add.22, f32[1024,3]{1,0} %dynamic-update-slice.24, s32[1]{0} %get-tuple-element.20), metadata={op_name="while"} } %region_1.27 (Arg_0.28: (s32[], s32[], f32[1024,3], s32[1])) -> pred[] { %Arg_0.28 = (s32[], s32[], f32[1024,3]{1,0}, s32[1]{0}) parameter(0) %get-tuple-element.30 = s32[] get-tuple-element((s32[], s32[], f32[1024,3]{1,0}, s32[1]{0}) %Arg_0.28), index=1, metadata={op_name="while"} %constant.29 = s32[] constant(1024) ROOT %compare.31 = pred[] compare(s32[] %get-tuple-element.30, s32[] %constant.29), direction=LT, metadata={op_name="while/Less"} } %region_2.42 (Arg_0.43: (f32[3,32,32,3], token[])) -> (pred[], token[]) { %constant.44 = pred[] constant(true) %Arg_0.43 = (f32[3,32,32,3]{3,2,1,0}, token[]) parameter(0) %get-tuple-element.52 = f32[3,32,32,3]{3,2,1,0} get-tuple-element((f32[3,32,32,3]{3,2,1,0}, token[]) %Arg_0.43), index=0, metadata={op_name="image_sample/write_summary/summary_cond"} %constant.49 = f32[] constant(255.5) %broadcast.50 = f32[3,32,32,3]{3,2,1,0} broadcast(f32[] %constant.49), dimensions={}, metadata={op_name="image_sample/write_summary/summary_cond/convert_image/Mul"} %multiply.53 = f32[3,32,32,3]{3,2,1,0} multiply(f32[3,32,32,3]{3,2,1,0} %get-tuple-element.52, f32[3,32,32,3]{3,2,1,0} %broadcast.50), metadata={op_name="image_sample/write_summary/summary_cond/convert_image/Mul"} %constant.47 = f32[] constant(0) %broadcast.48 = f32[3,32,32,3]{3,2,1,0} broadcast(f32[] %constant.47), dimensions={}, metadata={op_name="image_sample/write_summary/summary_cond/convert_image/Maximum"} %maximum.54 = f32[3,32,32,3]{3,2,1,0} maximum(f32[3,32,32,3]{3,2,1,0} %multiply.53, f32[3,32,32,3]{3,2,1,0} %broadcast.48), metadata={op_name="image_sample/write_summary/summary_cond/convert_image/Maximum"} %constant.45 = f32[] constant(255) %broadcast.46 = f32[3,32,32,3]{3,2,1,0} broadcast(f32[] %constant.45), dimensions={}, metadata={op_name="image_sample/write_summary/summary_cond/convert_image/Minimum"} %minimum.55 = f32[3,32,32,3]{3,2,1,0} minimum(f32[3,32,32,3]{3,2,1,0} %maximum.54, f32[3,32,32,3]{3,2,1,0} %broadcast.46), metadata={op_name="image_sample/write_summary/summary_cond/convert_image/Minimum"} %convert.56 = u8[3,32,32,3]{3,2,1,0} convert(f32[3,32,32,3]{3,2,1,0} %minimum.55), metadata={op_name="image_sample/write_summary/summary_cond/convert_image"} %get-tuple-element.51 = token[] get-tuple-element((f32[3,32,32,3]{3,2,1,0}, token[]) %Arg_0.43), index=1, metadata={op_name="image_sample/write_summary/summary_cond"} %send.57 = (u8[3,32,32,3]{3,2,1,0}, u32[], token[]) send(u8[3,32,32,3]{3,2,1,0} %convert.56, token[] %get-tuple-element.51), channel_id=2, is_host_transfer=true, frontend_attributes={_xla_host_transfer_rendezvous="host_compute_channel_0_args_dtoh_0"}, metadata={op_name="image_sample/write_summary/summary_cond/encode_each_image/TensorArrayUnstack/TensorListFromTensor"} %send-done.58 = token[] send-done((u8[3,32,32,3]{3,2,1,0}, u32[], token[]) %send.57), channel_id=2, is_host_transfer=true, frontend_attributes={_xla_host_transfer_rendezvous="host_compute_channel_0_args_dtoh_0"}, metadata={op_name="image_sample/write_summary/summary_cond/encode_each_image/TensorArrayUnstack/TensorListFromTensor"} ROOT %tuple.59 = (pred[], token[]) tuple(pred[] %constant.44, token[] %send-done.58), metadata={op_name="image_sample/write_summary/summary_cond"} } %region_3.60 (Arg_0.61: (f32[3,32,32,3], token[])) -> (pred[], token[]) { %constant.62 = pred[] constant(false) %Arg_0.61 = (f32[3,32,32,3]{3,2,1,0}, token[]) parameter(0) %get-tuple-element.63 = token[] get-tuple-element((f32[3,32,32,3]{3,2,1,0}, token[]) %Arg_0.61), index=1, metadata={op_name="image_sample/write_summary/summary_cond"} ROOT %tuple.64 = (pred[], token[]) tuple(pred[] %constant.62, token[] %get-tuple-element.63), metadata={op_name="image_sample/write_summary/summary_cond"} } ENTRY %main.67 (arg_tuple.1: (s32[])) -> () { %arg_tuple.1 = (s32[]{:T(256)}) parameter(0) %get-tuple-element.2 = s32[]{:T(256)} get-tuple-element((s32[]{:T(256)}) %arg_tuple.1), index=0 %constant.3 = s32[] constant(0) %compare.8 = pred[]{:T(256)} compare(s32[]{:T(256)} %get-tuple-element.2, s32[] %constant.3), direction=EQ, metadata={op_name="image_sample/write_summary/Equal"} %constant.5 = f32[] constant(0) %broadcast.6 = f32[1024,3]{1,0} broadcast(f32[] %constant.5), dimensions={}, metadata={op_name="tokens_accumulator"} %constant.4 = s32[1]{0} constant({1024}) %tuple.9 = (s32[], s32[], f32[1024,3]{1,0}, s32[1]{0}) tuple(s32[] %constant.3, s32[] %constant.3, f32[1024,3]{1,0} %broadcast.6, s32[1]{0} %constant.4), metadata={op_name="while"} %while.32 = (s32[], s32[], f32[1024,3]{1,0}, s32[1]{0}) while((s32[], s32[], f32[1024,3]{1,0}, s32[1]{0}) %tuple.9), condition=%region_1.27, body=%region_0.10, metadata={op_name="while"} %get-tuple-element.33 = f32[1024,3]{1,0} get-tuple-element((s32[], s32[], f32[1024,3]{1,0}, s32[1]{0}) %while.32), index=2, metadata={op_name="while"} %transpose.34 = f32[3,1024]{0,1} transpose(f32[1024,3]{1,0} %get-tuple-element.33), dimensions={1,0}, metadata={op_name="transpose.transpose/perm"} %reshape.35 = f32[3,32,32,1]{3,2,1,0} reshape(f32[3,1024]{0,1} %transpose.34), metadata={op_name="Reshape"} %broadcast.36 = f32[3,32,32,1]{3,2,1,0} broadcast(f32[3,32,32,1]{3,2,1,0} %reshape.35), dimensions={0,1,2,3}, metadata={op_name="Tile"} %reshape.37 = f32[3,32,32]{2,1,0} reshape(f32[3,32,32,1]{3,2,1,0} %broadcast.36), metadata={op_name="Tile"} %broadcast.38 = f32[3,32,32,3]{3,2,1,0} broadcast(f32[3,32,32]{2,1,0} %reshape.37), dimensions={0,1,2}, metadata={op_name="Tile"} %after-all.7 = token[] after-all(), metadata={op_name="image_sample/write_summary/summary_cond"} %send.39 = (pred[]{:T(256)}, u32[], token[]) send(pred[]{:T(256)} %compare.8, token[] %after-all.7), channel_id=1, is_host_transfer=true, frontend_attributes={_xla_host_transfer_rendezvous="if_predicate_channel_1_dtoh_0"}, metadata={op_name="image_sample/write_summary/summary_cond"} %send-done.40 = token[] send-done((pred[]{:T(256)}, u32[], token[]) %send.39), channel_id=1, is_host_transfer=true, frontend_attributes={_xla_host_transfer_rendezvous="if_predicate_channel_1_dtoh_0"}, metadata={op_name="image_sample/write_summary/summary_cond"} %tuple.41 = (f32[3,32,32,3]{3,2,1,0}, token[]) tuple(f32[3,32,32,3]{3,2,1,0} %broadcast.38, token[] %send-done.40), metadata={op_name="image_sample/write_summary/summary_cond"} %conditional.65 = (pred[], token[]) conditional(pred[]{:T(256)} %compare.8, (f32[3,32,32,3]{3,2,1,0}, token[]) %tuple.41, (f32[3,32,32,3]{3,2,1,0}, token[]) %tuple.41), true_computation=%region_2.42, false_computation=%region_3.60, metadata={op_name="image_sample/write_summary/summary_cond"} ROOT %tuple.66 = () tuple() } )") .value(); const HloLivenessAnalysis& liveness = RunLiveness(module.get()); EXPECT_TRUE( liveness.IsLive(GetInstruction(module.get(), "conditional.65"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.41"), {})); EXPECT_TRUE(liveness.IsLive( GetInstruction(module.get(), "get-tuple-element.33"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "while.32"), {})); EXPECT_TRUE(liveness.IsLive( GetInstruction(module.get(), "dynamic-update-slice.24"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "send.57"), {})); }
HloLivenessAnalysisTest_TupleAtEntryRoot
xla/service/hlo_liveness_analysis_test.cc
void AddToWorklist(const HloInstruction* instruction, Worklist* worklist, Workset* workset) { if (workset->insert(instruction).second) { worklist->push_back(instruction); VLOG(3) << "ADD instruction: " << instruction->name(); } } VLOG(3) << "ADD instruction: " << instruction->name(); void MarkLiveAtIndex(const HloInstruction* instruction, const ShapeIndex& shape_index, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/false); } bool& alive = *liveness->mutable_element(shape_index); if (!alive) { AddToWorklist(instruction, worklist, workset); alive = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << shape_index; } } VLOG(3) << "MARK instruction: " << instruction->name() void MarkLiveAtAllIndices(const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { bool add_to_worklist = false; std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/true); add_to_worklist = true; } else { for (auto& entry : *liveness) { if (!entry.second) { add_to_worklist = true; entry.second = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << entry.first; } } } if (add_to_worklist) { AddToWorklist(instruction, worklist, workset); } } VLOG(3) << "MARK instruction: " << instruction->name() void PropagateLivenessThroughTuple( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kTuple); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughGTE( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kGetTupleElement); // Mark operand top-level index. MarkLiveAtIndex(instruction->operand(0), {}, live_index_map, worklist, workset); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); // Propagate live shape indices along GTE -> Tuple edge. ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughWhile( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kWhile); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); // Propagate liveness to while condition computation root instruction. MarkLiveAtIndex(instruction->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessToParameterCallers( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { CHECK_EQ(instruction->opcode(), HloOpcode::kParameter); const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { if (callsite.instruction()->opcode() == HloOpcode::kWhile) { auto* xla_while = callsite.instruction(); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughControlFlow( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { HloInstruction* caller = callsite.instruction(); if (caller->opcode() == HloOpcode::kWhile) { // If a live instruction is within the %while body or condition // computation, mark the predicate value returned by the condition // computation live as well. MarkLiveAtIndex(caller->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } else if (caller->opcode() == HloOpcode::kConditional) { // If a live instruction is within the true or false branches of a // conditional, we mark the predicate operand live as well. MarkLiveAtIndex(caller->operand(0), {}, live_index_map, worklist, workset); // Mark the caller instruction live. MarkLiveAtIndex(caller, {}, live_index_map, worklist, workset); // Propagate liveness to the caller computation. const HloComputation* callee_comp = instruction->parent(); // Initialize 'operand_index' to skip predictate operand. int64_t operand_index = 1; for (auto* caller_comp : caller->called_computations()) { if (callee_comp == caller_comp) { MarkLiveAtIndex(caller->operand(operand_index), {}, live_index_map, worklist, workset); if (instruction->opcode() == HloOpcode::kParameter) { // If 'instruction' is a parameter, propagate live shape indices // to the associated callsite's argument shape indices. const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); } break; } ++operand_index; } } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); HloLivenessAnalysis::HloLivenessAnalysis(const HloModule& module) : module_(module), call_graph_(CallGraph::Build(&module)) {} void HloLivenessAnalysis::RunAnalysis() { Worklist worklist; Workset workset; // Add entry computation root instruction. MarkLiveAtAllIndices(module_.entry_computation()->root_instruction(), &live_index_map_, &worklist, &workset); for (auto* computation : module_.computations()) { for (auto* instruction : computation->instructions()) { if (instruction->HasSideEffectNoRecurse()) { // Add instructions with side effects. MarkLiveAtAllIndices(instruction, &live_index_map_, &worklist, &workset); } } } while (!worklist.empty()) { const HloInstruction* instruction = worklist.front(); worklist.pop_front(); workset.erase(workset.find(instruction)); VLOG(1) << "VISIT instruction: " << instruction->name(); if (instruction->opcode() == HloOpcode::kTuple) { PropagateLivenessThroughTuple(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kGetTupleElement) { PropagateLivenessThroughGTE(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kWhile) { PropagateLivenessThroughWhile(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kParameter) { PropagateLivenessToParameterCallers(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } else { // Propagate liveness to called computations. for (auto* called_computation : instruction->called_computations()) { MarkLiveAtAllIndices(called_computation->root_instruction(), &live_index_map_, &worklist, &workset); } // Propagate liveness to operands. for (HloInstruction* operand : instruction->operands()) { MarkLiveAtAllIndices(operand, &live_index_map_, &worklist, &workset); } } PropagateLivenessThroughControlFlow(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } } VLOG(1) << "VISIT instruction: " << instruction->name(); bool HloLivenessAnalysis::IsLive(const HloInstruction* instruction, const ShapeIndex& shape_index) const { auto it = live_index_map_.find(instruction); return (it != live_index_map_.end()) && it->second->element(shape_index); } absl::StatusOr<std::unique_ptr<HloLivenessAnalysis>> HloLivenessAnalysis::Run( const HloModule& module) { VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString()); auto liveness_analysis = absl::WrapUnique(new HloLivenessAnalysis(module)); liveness_analysis->RunAnalysis(); return std::move(liveness_analysis); } VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString());
#include "xla/service/hlo_liveness_analysis.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class HloLivenessAnalysisTest : public HloTestBase { protected: HloLivenessAnalysisTest() {} // Run liveness analysis on the member module. For convenience returns a // reference to the generated analysis stored in analysis_. const HloLivenessAnalysis& RunLiveness(HloModule* module) { liveness_ = HloLivenessAnalysis::Run(*module).value(); return *liveness_; } HloInstruction* GetInstruction(HloModule* module, const std::string& name) { HloInstruction* to_return = nullptr; for (auto* comp : module->computations()) { for (auto* inst : comp->instructions()) { if (inst->name() == name) { to_return = inst; break; } } } return CHECK_NOTNULL(to_return); } std::unique_ptr<HloLivenessAnalysis> liveness_; }; TEST_F(HloLivenessAnalysisTest, TupleAtEntryRoot) { auto module = ParseAndReturnVerifiedModule(R"( HloModule SimpleModule ENTRY SimpleComputation { constant.1 = s32[] constant(0) constant.2 = s32[] constant(1) ROOT tuple.1 = (s32[], s32[]) tuple(constant.1, constant.2) })") .value(); const HloLivenessAnalysis& liveness = RunLiveness(module.get()); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.2"), {})); }
HloLivenessAnalysisTest_WhileCondPropagatesLiveness
xla/service/hlo_liveness_analysis_test.cc
void AddToWorklist(const HloInstruction* instruction, Worklist* worklist, Workset* workset) { if (workset->insert(instruction).second) { worklist->push_back(instruction); VLOG(3) << "ADD instruction: " << instruction->name(); } } VLOG(3) << "ADD instruction: " << instruction->name(); void MarkLiveAtIndex(const HloInstruction* instruction, const ShapeIndex& shape_index, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/false); } bool& alive = *liveness->mutable_element(shape_index); if (!alive) { AddToWorklist(instruction, worklist, workset); alive = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << shape_index; } } VLOG(3) << "MARK instruction: " << instruction->name() void MarkLiveAtAllIndices(const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { bool add_to_worklist = false; std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/true); add_to_worklist = true; } else { for (auto& entry : *liveness) { if (!entry.second) { add_to_worklist = true; entry.second = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << entry.first; } } } if (add_to_worklist) { AddToWorklist(instruction, worklist, workset); } } VLOG(3) << "MARK instruction: " << instruction->name() void PropagateLivenessThroughTuple( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kTuple); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughGTE( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kGetTupleElement); // Mark operand top-level index. MarkLiveAtIndex(instruction->operand(0), {}, live_index_map, worklist, workset); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); // Propagate live shape indices along GTE -> Tuple edge. ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughWhile( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kWhile); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); // Propagate liveness to while condition computation root instruction. MarkLiveAtIndex(instruction->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessToParameterCallers( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { CHECK_EQ(instruction->opcode(), HloOpcode::kParameter); const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { if (callsite.instruction()->opcode() == HloOpcode::kWhile) { auto* xla_while = callsite.instruction(); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughControlFlow( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { HloInstruction* caller = callsite.instruction(); if (caller->opcode() == HloOpcode::kWhile) { // If a live instruction is within the %while body or condition // computation, mark the predicate value returned by the condition // computation live as well. MarkLiveAtIndex(caller->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } else if (caller->opcode() == HloOpcode::kConditional) { // If a live instruction is within the true or false branches of a // conditional, we mark the predicate operand live as well. MarkLiveAtIndex(caller->operand(0), {}, live_index_map, worklist, workset); // Mark the caller instruction live. MarkLiveAtIndex(caller, {}, live_index_map, worklist, workset); // Propagate liveness to the caller computation. const HloComputation* callee_comp = instruction->parent(); // Initialize 'operand_index' to skip predictate operand. int64_t operand_index = 1; for (auto* caller_comp : caller->called_computations()) { if (callee_comp == caller_comp) { MarkLiveAtIndex(caller->operand(operand_index), {}, live_index_map, worklist, workset); if (instruction->opcode() == HloOpcode::kParameter) { // If 'instruction' is a parameter, propagate live shape indices // to the associated callsite's argument shape indices. const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); } break; } ++operand_index; } } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); HloLivenessAnalysis::HloLivenessAnalysis(const HloModule& module) : module_(module), call_graph_(CallGraph::Build(&module)) {} void HloLivenessAnalysis::RunAnalysis() { Worklist worklist; Workset workset; // Add entry computation root instruction. MarkLiveAtAllIndices(module_.entry_computation()->root_instruction(), &live_index_map_, &worklist, &workset); for (auto* computation : module_.computations()) { for (auto* instruction : computation->instructions()) { if (instruction->HasSideEffectNoRecurse()) { // Add instructions with side effects. MarkLiveAtAllIndices(instruction, &live_index_map_, &worklist, &workset); } } } while (!worklist.empty()) { const HloInstruction* instruction = worklist.front(); worklist.pop_front(); workset.erase(workset.find(instruction)); VLOG(1) << "VISIT instruction: " << instruction->name(); if (instruction->opcode() == HloOpcode::kTuple) { PropagateLivenessThroughTuple(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kGetTupleElement) { PropagateLivenessThroughGTE(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kWhile) { PropagateLivenessThroughWhile(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kParameter) { PropagateLivenessToParameterCallers(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } else { // Propagate liveness to called computations. for (auto* called_computation : instruction->called_computations()) { MarkLiveAtAllIndices(called_computation->root_instruction(), &live_index_map_, &worklist, &workset); } // Propagate liveness to operands. for (HloInstruction* operand : instruction->operands()) { MarkLiveAtAllIndices(operand, &live_index_map_, &worklist, &workset); } } PropagateLivenessThroughControlFlow(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } } VLOG(1) << "VISIT instruction: " << instruction->name(); bool HloLivenessAnalysis::IsLive(const HloInstruction* instruction, const ShapeIndex& shape_index) const { auto it = live_index_map_.find(instruction); return (it != live_index_map_.end()) && it->second->element(shape_index); } absl::StatusOr<std::unique_ptr<HloLivenessAnalysis>> HloLivenessAnalysis::Run( const HloModule& module) { VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString()); auto liveness_analysis = absl::WrapUnique(new HloLivenessAnalysis(module)); liveness_analysis->RunAnalysis(); return std::move(liveness_analysis); } VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString());
#include "xla/service/hlo_liveness_analysis.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class HloLivenessAnalysisTest : public HloTestBase { protected: HloLivenessAnalysisTest() {} // Run liveness analysis on the member module. For convenience returns a // reference to the generated analysis stored in analysis_. const HloLivenessAnalysis& RunLiveness(HloModule* module) { liveness_ = HloLivenessAnalysis::Run(*module).value(); return *liveness_; } HloInstruction* GetInstruction(HloModule* module, const std::string& name) { HloInstruction* to_return = nullptr; for (auto* comp : module->computations()) { for (auto* inst : comp->instructions()) { if (inst->name() == name) { to_return = inst; break; } } } return CHECK_NOTNULL(to_return); } std::unique_ptr<HloLivenessAnalysis> liveness_; }; TEST_F(HloLivenessAnalysisTest, WhileCondPropagatesLiveness) { auto module = ParseAndReturnVerifiedModule(R"( HloModule SimpleLoop add_S32 { lhs = s32[] parameter(0) rhs = s32[] parameter(1) ROOT add = s32[] add(lhs, rhs) } SimpleLoop.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.0 = s32[] add(get-tuple-element.1, constant.1) get-tuple-element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1 multiply.0 = s32[3]{0} multiply(get-tuple-element.2, get-tuple-element.2) ROOT tuple.0 = (s32[], s32[3]{0}) tuple(add.0, multiply.0) } SimpleLoop.condition { loop_var.2 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.3 = s32[] get-tuple-element(loop_var.2), index=0 get-tuple-element.4 = s32[3]{0} get-tuple-element(loop_var.2), index=1 zero = s32[] constant(0) reduce = s32[] reduce(get-tuple-element.4, zero), dimensions={0}, to_apply=add_S32 add.1 = s32[] add(get-tuple-element.3, reduce) constant.2 = s32[] constant(5) ROOT less-than = pred[] compare(add.1, constant.2), direction=LT } ENTRY SimpleLoop { constant.3 = s32[] constant(0) constant.4 = s32[3]{0} constant({0, 1, 2}) tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4) while.0 = (s32[], s32[3]{0}) while(tuple.1), condition= SimpleLoop.condition, body=SimpleLoop.body ROOT get-tuple-element.5 = s32[] get-tuple-element(while.0), index=0 })") .value(); const HloLivenessAnalysis& liveness = RunLiveness(module.get()); EXPECT_TRUE( liveness.IsLive(GetInstruction(module.get(), "get-tuple-element.5"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "while.0"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "while.0"), {0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "while.0"), {1})); // While operand. EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.3"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.4"), {})); // While body. EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.0"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.0"), {0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.0"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "add.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "multiply.0"), {})); }
HloLivenessAnalysisTest_WhileWithDeadTupleElement
xla/service/hlo_liveness_analysis_test.cc
void AddToWorklist(const HloInstruction* instruction, Worklist* worklist, Workset* workset) { if (workset->insert(instruction).second) { worklist->push_back(instruction); VLOG(3) << "ADD instruction: " << instruction->name(); } } VLOG(3) << "ADD instruction: " << instruction->name(); void MarkLiveAtIndex(const HloInstruction* instruction, const ShapeIndex& shape_index, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/false); } bool& alive = *liveness->mutable_element(shape_index); if (!alive) { AddToWorklist(instruction, worklist, workset); alive = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << shape_index; } } VLOG(3) << "MARK instruction: " << instruction->name() void MarkLiveAtAllIndices(const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { bool add_to_worklist = false; std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/true); add_to_worklist = true; } else { for (auto& entry : *liveness) { if (!entry.second) { add_to_worklist = true; entry.second = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << entry.first; } } } if (add_to_worklist) { AddToWorklist(instruction, worklist, workset); } } VLOG(3) << "MARK instruction: " << instruction->name() void PropagateLivenessThroughTuple( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kTuple); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughGTE( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kGetTupleElement); // Mark operand top-level index. MarkLiveAtIndex(instruction->operand(0), {}, live_index_map, worklist, workset); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); // Propagate live shape indices along GTE -> Tuple edge. ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughWhile( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kWhile); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); // Propagate liveness to while condition computation root instruction. MarkLiveAtIndex(instruction->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessToParameterCallers( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { CHECK_EQ(instruction->opcode(), HloOpcode::kParameter); const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { if (callsite.instruction()->opcode() == HloOpcode::kWhile) { auto* xla_while = callsite.instruction(); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughControlFlow( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { HloInstruction* caller = callsite.instruction(); if (caller->opcode() == HloOpcode::kWhile) { // If a live instruction is within the %while body or condition // computation, mark the predicate value returned by the condition // computation live as well. MarkLiveAtIndex(caller->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } else if (caller->opcode() == HloOpcode::kConditional) { // If a live instruction is within the true or false branches of a // conditional, we mark the predicate operand live as well. MarkLiveAtIndex(caller->operand(0), {}, live_index_map, worklist, workset); // Mark the caller instruction live. MarkLiveAtIndex(caller, {}, live_index_map, worklist, workset); // Propagate liveness to the caller computation. const HloComputation* callee_comp = instruction->parent(); // Initialize 'operand_index' to skip predictate operand. int64_t operand_index = 1; for (auto* caller_comp : caller->called_computations()) { if (callee_comp == caller_comp) { MarkLiveAtIndex(caller->operand(operand_index), {}, live_index_map, worklist, workset); if (instruction->opcode() == HloOpcode::kParameter) { // If 'instruction' is a parameter, propagate live shape indices // to the associated callsite's argument shape indices. const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); } break; } ++operand_index; } } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); HloLivenessAnalysis::HloLivenessAnalysis(const HloModule& module) : module_(module), call_graph_(CallGraph::Build(&module)) {} void HloLivenessAnalysis::RunAnalysis() { Worklist worklist; Workset workset; // Add entry computation root instruction. MarkLiveAtAllIndices(module_.entry_computation()->root_instruction(), &live_index_map_, &worklist, &workset); for (auto* computation : module_.computations()) { for (auto* instruction : computation->instructions()) { if (instruction->HasSideEffectNoRecurse()) { // Add instructions with side effects. MarkLiveAtAllIndices(instruction, &live_index_map_, &worklist, &workset); } } } while (!worklist.empty()) { const HloInstruction* instruction = worklist.front(); worklist.pop_front(); workset.erase(workset.find(instruction)); VLOG(1) << "VISIT instruction: " << instruction->name(); if (instruction->opcode() == HloOpcode::kTuple) { PropagateLivenessThroughTuple(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kGetTupleElement) { PropagateLivenessThroughGTE(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kWhile) { PropagateLivenessThroughWhile(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kParameter) { PropagateLivenessToParameterCallers(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } else { // Propagate liveness to called computations. for (auto* called_computation : instruction->called_computations()) { MarkLiveAtAllIndices(called_computation->root_instruction(), &live_index_map_, &worklist, &workset); } // Propagate liveness to operands. for (HloInstruction* operand : instruction->operands()) { MarkLiveAtAllIndices(operand, &live_index_map_, &worklist, &workset); } } PropagateLivenessThroughControlFlow(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } } VLOG(1) << "VISIT instruction: " << instruction->name(); bool HloLivenessAnalysis::IsLive(const HloInstruction* instruction, const ShapeIndex& shape_index) const { auto it = live_index_map_.find(instruction); return (it != live_index_map_.end()) && it->second->element(shape_index); } absl::StatusOr<std::unique_ptr<HloLivenessAnalysis>> HloLivenessAnalysis::Run( const HloModule& module) { VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString()); auto liveness_analysis = absl::WrapUnique(new HloLivenessAnalysis(module)); liveness_analysis->RunAnalysis(); return std::move(liveness_analysis); } VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString());
#include "xla/service/hlo_liveness_analysis.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class HloLivenessAnalysisTest : public HloTestBase { protected: HloLivenessAnalysisTest() {} // Run liveness analysis on the member module. For convenience returns a // reference to the generated analysis stored in analysis_. const HloLivenessAnalysis& RunLiveness(HloModule* module) { liveness_ = HloLivenessAnalysis::Run(*module).value(); return *liveness_; } HloInstruction* GetInstruction(HloModule* module, const std::string& name) { HloInstruction* to_return = nullptr; for (auto* comp : module->computations()) { for (auto* inst : comp->instructions()) { if (inst->name() == name) { to_return = inst; break; } } } return CHECK_NOTNULL(to_return); } std::unique_ptr<HloLivenessAnalysis> liveness_; }; TEST_F(HloLivenessAnalysisTest, WhileWithDeadTupleElement) { auto module = ParseAndReturnVerifiedModule(R"( HloModule SimpleLoop SimpleLoop.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.0 = s32[] add(get-tuple-element.1, constant.1) get-tuple-element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1 multiply.0 = s32[3]{0} multiply(get-tuple-element.2, get-tuple-element.2) ROOT tuple.0 = (s32[], s32[3]{0}) tuple(add.0, multiply.0) } SimpleLoop.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(5) ROOT less-than = pred[] compare(get-tuple-element.3, constant.2), direction=LT } ENTRY SimpleLoop { constant.3 = s32[] constant(0) constant.4 = s32[3]{0} constant({0, 1, 2}) tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4) while.0 = (s32[], s32[3]{0}) while(tuple.1), condition= SimpleLoop.condition, body=SimpleLoop.body ROOT get-tuple-element.4 = s32[] get-tuple-element(while.0), index=0 })") .value(); const HloLivenessAnalysis& liveness = RunLiveness(module.get()); EXPECT_TRUE( liveness.IsLive(GetInstruction(module.get(), "get-tuple-element.4"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "while.0"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "while.0"), {0})); EXPECT_FALSE(liveness.IsLive(GetInstruction(module.get(), "while.0"), {1})); // While operand. EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {0})); EXPECT_FALSE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.3"), {})); // While body. EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.0"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.0"), {0})); EXPECT_FALSE(liveness.IsLive(GetInstruction(module.get(), "tuple.0"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "add.0"), {})); EXPECT_FALSE(liveness.IsLive(GetInstruction(module.get(), "multiply.0"), {})); }
HloLivenessAnalysisTest_WhileWithLiveTupleElements
xla/service/hlo_liveness_analysis_test.cc
void AddToWorklist(const HloInstruction* instruction, Worklist* worklist, Workset* workset) { if (workset->insert(instruction).second) { worklist->push_back(instruction); VLOG(3) << "ADD instruction: " << instruction->name(); } } VLOG(3) << "ADD instruction: " << instruction->name(); void MarkLiveAtIndex(const HloInstruction* instruction, const ShapeIndex& shape_index, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/false); } bool& alive = *liveness->mutable_element(shape_index); if (!alive) { AddToWorklist(instruction, worklist, workset); alive = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << shape_index; } } VLOG(3) << "MARK instruction: " << instruction->name() void MarkLiveAtAllIndices(const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { bool add_to_worklist = false; std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/true); add_to_worklist = true; } else { for (auto& entry : *liveness) { if (!entry.second) { add_to_worklist = true; entry.second = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << entry.first; } } } if (add_to_worklist) { AddToWorklist(instruction, worklist, workset); } } VLOG(3) << "MARK instruction: " << instruction->name() void PropagateLivenessThroughTuple( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kTuple); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughGTE( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kGetTupleElement); // Mark operand top-level index. MarkLiveAtIndex(instruction->operand(0), {}, live_index_map, worklist, workset); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); // Propagate live shape indices along GTE -> Tuple edge. ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughWhile( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kWhile); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); // Propagate liveness to while condition computation root instruction. MarkLiveAtIndex(instruction->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessToParameterCallers( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { CHECK_EQ(instruction->opcode(), HloOpcode::kParameter); const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { if (callsite.instruction()->opcode() == HloOpcode::kWhile) { auto* xla_while = callsite.instruction(); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughControlFlow( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { HloInstruction* caller = callsite.instruction(); if (caller->opcode() == HloOpcode::kWhile) { // If a live instruction is within the %while body or condition // computation, mark the predicate value returned by the condition // computation live as well. MarkLiveAtIndex(caller->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } else if (caller->opcode() == HloOpcode::kConditional) { // If a live instruction is within the true or false branches of a // conditional, we mark the predicate operand live as well. MarkLiveAtIndex(caller->operand(0), {}, live_index_map, worklist, workset); // Mark the caller instruction live. MarkLiveAtIndex(caller, {}, live_index_map, worklist, workset); // Propagate liveness to the caller computation. const HloComputation* callee_comp = instruction->parent(); // Initialize 'operand_index' to skip predictate operand. int64_t operand_index = 1; for (auto* caller_comp : caller->called_computations()) { if (callee_comp == caller_comp) { MarkLiveAtIndex(caller->operand(operand_index), {}, live_index_map, worklist, workset); if (instruction->opcode() == HloOpcode::kParameter) { // If 'instruction' is a parameter, propagate live shape indices // to the associated callsite's argument shape indices. const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); } break; } ++operand_index; } } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); HloLivenessAnalysis::HloLivenessAnalysis(const HloModule& module) : module_(module), call_graph_(CallGraph::Build(&module)) {} void HloLivenessAnalysis::RunAnalysis() { Worklist worklist; Workset workset; // Add entry computation root instruction. MarkLiveAtAllIndices(module_.entry_computation()->root_instruction(), &live_index_map_, &worklist, &workset); for (auto* computation : module_.computations()) { for (auto* instruction : computation->instructions()) { if (instruction->HasSideEffectNoRecurse()) { // Add instructions with side effects. MarkLiveAtAllIndices(instruction, &live_index_map_, &worklist, &workset); } } } while (!worklist.empty()) { const HloInstruction* instruction = worklist.front(); worklist.pop_front(); workset.erase(workset.find(instruction)); VLOG(1) << "VISIT instruction: " << instruction->name(); if (instruction->opcode() == HloOpcode::kTuple) { PropagateLivenessThroughTuple(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kGetTupleElement) { PropagateLivenessThroughGTE(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kWhile) { PropagateLivenessThroughWhile(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kParameter) { PropagateLivenessToParameterCallers(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } else { // Propagate liveness to called computations. for (auto* called_computation : instruction->called_computations()) { MarkLiveAtAllIndices(called_computation->root_instruction(), &live_index_map_, &worklist, &workset); } // Propagate liveness to operands. for (HloInstruction* operand : instruction->operands()) { MarkLiveAtAllIndices(operand, &live_index_map_, &worklist, &workset); } } PropagateLivenessThroughControlFlow(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } } VLOG(1) << "VISIT instruction: " << instruction->name(); bool HloLivenessAnalysis::IsLive(const HloInstruction* instruction, const ShapeIndex& shape_index) const { auto it = live_index_map_.find(instruction); return (it != live_index_map_.end()) && it->second->element(shape_index); } absl::StatusOr<std::unique_ptr<HloLivenessAnalysis>> HloLivenessAnalysis::Run( const HloModule& module) { VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString()); auto liveness_analysis = absl::WrapUnique(new HloLivenessAnalysis(module)); liveness_analysis->RunAnalysis(); return std::move(liveness_analysis); } VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString());
#include "xla/service/hlo_liveness_analysis.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class HloLivenessAnalysisTest : public HloTestBase { protected: HloLivenessAnalysisTest() {} // Run liveness analysis on the member module. For convenience returns a // reference to the generated analysis stored in analysis_. const HloLivenessAnalysis& RunLiveness(HloModule* module) { liveness_ = HloLivenessAnalysis::Run(*module).value(); return *liveness_; } HloInstruction* GetInstruction(HloModule* module, const std::string& name) { HloInstruction* to_return = nullptr; for (auto* comp : module->computations()) { for (auto* inst : comp->instructions()) { if (inst->name() == name) { to_return = inst; break; } } } return CHECK_NOTNULL(to_return); } std::unique_ptr<HloLivenessAnalysis> liveness_; }; TEST_F(HloLivenessAnalysisTest, WhileWithLiveTupleElements) { auto module = ParseAndReturnVerifiedModule(R"( HloModule SimpleLoop SimpleLoop.body { loop_var.1 = (s32[], s32[], s32[]) parameter(0) get-tuple-element.1 = s32[] get-tuple-element(loop_var.1), index=0 get-tuple-element.2 = s32[] get-tuple-element(loop_var.1), index=1 add.1 = s32[] add(get-tuple-element.1, get-tuple-element.2) get-tuple-element.3 = s32[] get-tuple-element(loop_var.1), index=2 multiply.1 = s32[] multiply(get-tuple-element.3, get-tuple-element.3) ROOT tuple.1 = (s32[], s32[], s32[]) tuple(add.1, get-tuple-element.3, multiply.1) } SimpleLoop.condition { loop_var.2 = (s32[], s32[], s32[]) parameter(0) get-tuple-element.4 = s32[] get-tuple-element(loop_var.2), index=0 constant.1 = s32[] constant(5) ROOT less-than = pred[] compare(get-tuple-element.4, constant.1), direction=LT } ENTRY SimpleLoop { constant.2 = s32[] constant(0) constant.3 = s32[] constant(1) constant.4 = s32[] constant(2) tuple.2 = (s32[], s32[], s32[]) tuple(constant.2, constant.3, constant.4) while.1 = (s32[], s32[], s32[]) while(tuple.2), condition= SimpleLoop.condition, body=SimpleLoop.body ROOT get-tuple-element.5 = s32[] get-tuple-element(while.1), index=0 })") .value(); const HloLivenessAnalysis& liveness = RunLiveness(module.get()); EXPECT_TRUE( liveness.IsLive(GetInstruction(module.get(), "get-tuple-element.5"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "while.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "while.1"), {0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "while.1"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "while.1"), {2})); // While operand. EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.2"), {2})); // While body root. EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "tuple.1"), {2})); // While body param. EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "loop_var.1"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "loop_var.1"), {0})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "loop_var.1"), {1})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "loop_var.1"), {2})); }
HloLivenessAnalysisTest_WhileWithOutfeed
xla/service/hlo_liveness_analysis_test.cc
void AddToWorklist(const HloInstruction* instruction, Worklist* worklist, Workset* workset) { if (workset->insert(instruction).second) { worklist->push_back(instruction); VLOG(3) << "ADD instruction: " << instruction->name(); } } VLOG(3) << "ADD instruction: " << instruction->name(); void MarkLiveAtIndex(const HloInstruction* instruction, const ShapeIndex& shape_index, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/false); } bool& alive = *liveness->mutable_element(shape_index); if (!alive) { AddToWorklist(instruction, worklist, workset); alive = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << shape_index; } } VLOG(3) << "MARK instruction: " << instruction->name() void MarkLiveAtAllIndices(const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { bool add_to_worklist = false; std::unique_ptr<ShapeTree<bool>>& liveness = (*live_index_map)[instruction]; if (liveness == nullptr) { liveness = std::make_unique<ShapeTree<bool>>(instruction->shape(), /*init_value=*/true); add_to_worklist = true; } else { for (auto& entry : *liveness) { if (!entry.second) { add_to_worklist = true; entry.second = true; VLOG(3) << "MARK instruction: " << instruction->name() << " shape_index: " << entry.first; } } } if (add_to_worklist) { AddToWorklist(instruction, worklist, workset); } } VLOG(3) << "MARK instruction: " << instruction->name() void PropagateLivenessThroughTuple( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kTuple); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { const size_t size = shape_index.size(); if (size == 0) { return; } const int64_t operand_index = shape_index[0]; if (operand_index >= instruction->operand_count()) { return; } // Mark top-level index of operand at 'operand_index'. MarkLiveAtIndex(instruction->operand(operand_index), {}, live_index_map, worklist, workset); // Mark sub-shape index of operand at 'operand_index'. ShapeIndex operand_shape_index(size - 1); for (int i = 1; i < size; ++i) { operand_shape_index[i - 1] = shape_index[i]; } MarkLiveAtIndex(instruction->operand(operand_index), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughGTE( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kGetTupleElement); // Mark operand top-level index. MarkLiveAtIndex(instruction->operand(0), {}, live_index_map, worklist, workset); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); // Propagate live shape indices along GTE -> Tuple edge. ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { ShapeIndex operand_shape_index(shape_index); operand_shape_index.push_front(instruction->tuple_index()); MarkLiveAtIndex(instruction->operand(0), operand_shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughWhile( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset) { CHECK_EQ(instruction->opcode(), HloOpcode::kWhile); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); // Propagate liveness to while condition computation root instruction. MarkLiveAtIndex(instruction->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while body computation root instruction. MarkLiveAtIndex(instruction->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to tuple-shaped operand. MarkLiveAtIndex(instruction->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessToParameterCallers( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { CHECK_EQ(instruction->opcode(), HloOpcode::kParameter); const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { if (callsite.instruction()->opcode() == HloOpcode::kWhile) { auto* xla_while = callsite.instruction(); const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { // Propagate liveness to while result{shape_index} MarkLiveAtIndex(xla_while, shape_index, live_index_map, worklist, workset); // Propagate liveness to while body root{shape_index}. MarkLiveAtIndex(xla_while->while_body()->root_instruction(), shape_index, live_index_map, worklist, workset); // Propagate liveness to operand(0){shape_index}. MarkLiveAtIndex(xla_while->operand(0), shape_index, live_index_map, worklist, workset); }); void PropagateLivenessThroughControlFlow( const HloInstruction* instruction, HloLivenessAnalysis::HloIndexMap* live_index_map, Worklist* worklist, Workset* workset, CallGraph* call_graph) { const CallGraphNode& call_graph_node = call_graph->GetNode(instruction->parent()); if (call_graph_node.context() == CallContext::kControlFlow) { for (const CallSite& callsite : call_graph_node.caller_callsites()) { HloInstruction* caller = callsite.instruction(); if (caller->opcode() == HloOpcode::kWhile) { // If a live instruction is within the %while body or condition // computation, mark the predicate value returned by the condition // computation live as well. MarkLiveAtIndex(caller->while_condition()->root_instruction(), {}, live_index_map, worklist, workset); } else if (caller->opcode() == HloOpcode::kConditional) { // If a live instruction is within the true or false branches of a // conditional, we mark the predicate operand live as well. MarkLiveAtIndex(caller->operand(0), {}, live_index_map, worklist, workset); // Mark the caller instruction live. MarkLiveAtIndex(caller, {}, live_index_map, worklist, workset); // Propagate liveness to the caller computation. const HloComputation* callee_comp = instruction->parent(); // Initialize 'operand_index' to skip predictate operand. int64_t operand_index = 1; for (auto* caller_comp : caller->called_computations()) { if (callee_comp == caller_comp) { MarkLiveAtIndex(caller->operand(operand_index), {}, live_index_map, worklist, workset); if (instruction->opcode() == HloOpcode::kParameter) { // If 'instruction' is a parameter, propagate live shape indices // to the associated callsite's argument shape indices. const ShapeTree<bool>& index_tree = *live_index_map->at(instruction); ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); } break; } ++operand_index; } } } } } ForEachLiveIndex(index_tree, [&](const ShapeIndex& shape_index) { MarkLiveAtIndex(caller->operand(operand_index), shape_index, live_index_map, worklist, workset); }); HloLivenessAnalysis::HloLivenessAnalysis(const HloModule& module) : module_(module), call_graph_(CallGraph::Build(&module)) {} void HloLivenessAnalysis::RunAnalysis() { Worklist worklist; Workset workset; // Add entry computation root instruction. MarkLiveAtAllIndices(module_.entry_computation()->root_instruction(), &live_index_map_, &worklist, &workset); for (auto* computation : module_.computations()) { for (auto* instruction : computation->instructions()) { if (instruction->HasSideEffectNoRecurse()) { // Add instructions with side effects. MarkLiveAtAllIndices(instruction, &live_index_map_, &worklist, &workset); } } } while (!worklist.empty()) { const HloInstruction* instruction = worklist.front(); worklist.pop_front(); workset.erase(workset.find(instruction)); VLOG(1) << "VISIT instruction: " << instruction->name(); if (instruction->opcode() == HloOpcode::kTuple) { PropagateLivenessThroughTuple(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kGetTupleElement) { PropagateLivenessThroughGTE(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kWhile) { PropagateLivenessThroughWhile(instruction, &live_index_map_, &worklist, &workset); } else if (instruction->opcode() == HloOpcode::kParameter) { PropagateLivenessToParameterCallers(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } else { // Propagate liveness to called computations. for (auto* called_computation : instruction->called_computations()) { MarkLiveAtAllIndices(called_computation->root_instruction(), &live_index_map_, &worklist, &workset); } // Propagate liveness to operands. for (HloInstruction* operand : instruction->operands()) { MarkLiveAtAllIndices(operand, &live_index_map_, &worklist, &workset); } } PropagateLivenessThroughControlFlow(instruction, &live_index_map_, &worklist, &workset, call_graph_.get()); } } VLOG(1) << "VISIT instruction: " << instruction->name(); bool HloLivenessAnalysis::IsLive(const HloInstruction* instruction, const ShapeIndex& shape_index) const { auto it = live_index_map_.find(instruction); return (it != live_index_map_.end()) && it->second->element(shape_index); } absl::StatusOr<std::unique_ptr<HloLivenessAnalysis>> HloLivenessAnalysis::Run( const HloModule& module) { VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString()); auto liveness_analysis = absl::WrapUnique(new HloLivenessAnalysis(module)); liveness_analysis->RunAnalysis(); return std::move(liveness_analysis); } VLOG(1) << "HloLivenessAnalysis::Run on module " << module.name(); XLA_VLOG_LINES(2, module.ToString());
#include "xla/service/hlo_liveness_analysis.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" class HloLivenessAnalysisTest : public HloTestBase { protected: HloLivenessAnalysisTest() {} // Run liveness analysis on the member module. For convenience returns a // reference to the generated analysis stored in analysis_. const HloLivenessAnalysis& RunLiveness(HloModule* module) { liveness_ = HloLivenessAnalysis::Run(*module).value(); return *liveness_; } HloInstruction* GetInstruction(HloModule* module, const std::string& name) { HloInstruction* to_return = nullptr; for (auto* comp : module->computations()) { for (auto* inst : comp->instructions()) { if (inst->name() == name) { to_return = inst; break; } } } return CHECK_NOTNULL(to_return); } std::unique_ptr<HloLivenessAnalysis> liveness_; }; TEST_F(HloLivenessAnalysisTest, WhileWithOutfeed) { auto module = ParseAndReturnVerifiedModule(R"( HloModule OutfeedLoop WhileBody { body_param = (s32[]) parameter(0) token0 = token[] after-all() constant.2 = s32[] constant(2) outfeed_tuple = (s32[]) outfeed(constant.2, token0) get-tuple-element.1 = s32[] get-tuple-element(body_param), index=0 constant.1 = s32[] constant(1) add = s32[] add(get-tuple-element.1, constant.1) ROOT tuple = (s32[]) tuple(add) } WhileCondition { cond_param = (s32[]) parameter(0) get-tuple-element.3 = s32[] get-tuple-element(cond_param), index=0 constant.2 = s32[] constant(10) ROOT less-than = pred[] compare(get-tuple-element.3, constant.2), direction=LT } ENTRY SimpleLoop { constant.3 = s32[] constant(0) tuple.1 = (s32[]) tuple(constant.3) while = (s32[]) while(tuple.1), condition=WhileCondition, body=WhileBody ROOT rtuple = () tuple() })") .value(); const HloLivenessAnalysis& liveness = RunLiveness(module.get()); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "add"), {})); EXPECT_TRUE(liveness.IsLive(GetInstruction(module.get(), "constant.3"), {})); }
HloParserTest_AliasingShapeIndexNotNumerical
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AliasingShapeIndexNotNumerical) { const std::string original = R"( HloModule Module, input_output_alias={ {0, a}: (0, {0}), {1}: (0, {1}) } ENTRY entry { %p = (f32[], f32[]) parameter(0) %p0 = f32[] get-tuple-element((f32[], f32[]) %p), index=0 %p1 = f32[] get-tuple-element((f32[], f32[]) %p), index=1 ROOT %out = (f32[], f32[]) tuple(%p0, %p1) } )"; ExpectHasSubstr(ParseAndReturnUnverifiedModule(original).status().message(), "expects integer"); }
HloParserTest_AliasingWrongFormatAlphaParam
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AliasingWrongFormatAlphaParam) { const std::string original = R"( HloModule Module, input_output_alias={ {0, a}: (zero, {0}), {1}: (0, {1}) } ENTRY entry { %p = (f32[], f32[]) parameter(0) %p0 = f32[] get-tuple-element((f32[], f32[]) %p), index=0 %p1 = f32[] get-tuple-element((f32[], f32[]) %p), index=1 ROOT %out = (f32[], f32[]) tuple(%p0, %p1) } )"; ExpectHasSubstr(ParseAndReturnUnverifiedModule(original).status().message(), "expects integer"); }
HloParserTest_AliasingWrongFormatNoColon
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } };
HloParserTest_AliasingWrongFormatTwoColons
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AliasingWrongFormatTwoColons) { const std::string original = R"( HloModule Module, input_output_alias={ {0}: (0, {0}): {0, 1}, {1}: (0, {1}) } ENTRY entry { %p = (f32[], f32[]) parameter(0) %p0 = f32[] get-tuple-element((f32[], f32[]) %p), index=0 %p1 = f32[] get-tuple-element((f32[], f32[]) %p), index=1 ROOT %out = (f32[], f32[]) tuple(%p0, %p1) } )"; ExpectHasSubstr(ParseAndReturnUnverifiedModule(original).status().message(), "Expects '}
HloParserTest_AliasingWrongIndex
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } };
HloParserTest_AllowShapeWhitespace
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AllowShapeWhitespace) { const std::string text = R"( HloModule module ENTRY entry { ROOT root = f32[ 1, 2,3, 4, 5]{0, 1, 2,3, 4 } parameter(0) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(text)); }
HloParserTest_AsyncDoneNoAsyncStart
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AsyncDoneNoAsyncStart) { const char* const hlo_string = R"( HloModule Module ENTRY AsyncStartAndAsyncDone { p0 = f32[2,3] parameter(0) p1 = u32[] parameter(1) tuple = ((f32[2,3]), f32[2,3], u32[]) tuple(p0, p0, p1) ROOT async-done = f32[2,3] custom-call-done(tuple) } )"; EXPECT_THAT( ParseAndReturnUnverifiedModule(hlo_string).status(), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, HasSubstr("AsyncUpdate and AsyncDone expect their operand to be " "the previous async op."))); }
HloParserTest_AsyncDoneWithSyntaxSugarWrongOp
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AsyncDoneWithSyntaxSugarWrongOp) { const char* const hlo_string = R"( HloModule AsyncUpdateWithSyntaxSugarWrongOp ENTRY %Entry (p0: f32[10]) -> f32[20] { %p0 = f32[10]{0} parameter(0) %async-start = ((f32[10]{0}), f32[20]{0}, s32[]) custom-call-start(f32[10]{0} %p0), custom_call_target="foo" %async-update = ((f32[10]{0}), f32[20]{0}, s32[]) custom-call-update(((f32[10]{0}), f32[20]{0}, s32[]) %async-start) ROOT %async-done = f32[20]{0} add-done(((f32[10]{0}), f32[20]{0}, s32[]) %async-update) } )"; EXPECT_THAT(ParseAndReturnUnverifiedModule(hlo_string).status(), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, HasSubstr("Expect async wrapped opcode to be custom-call, " "but got add"))); }
HloParserTest_AsyncDoneWrongComputation
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AsyncDoneWrongComputation) { const char* const hlo_string = R"( HloModule AsyncDoneWrongComputation %async_wrapped.0 (async_param: f32[10]) -> f32[20] { %async_param = f32[10]{0} parameter(0) ROOT %custom-call = f32[20]{0} custom-call(f32[10]{0} %async_param), custom_call_target="foo" } %async_wrapped.1 (async_param: f32[10]) -> f32[20] { %async_param = f32[10]{0} parameter(0) ROOT %custom-call = f32[20]{0} custom-call(f32[10]{0} %async_param), custom_call_target="foo" } ENTRY %Entry (p0: f32[10]) -> f32[20] { %p0 = f32[10]{0} parameter(0) %async-start = ((f32[10]{0}), f32[20]{0}, s32[]) async-start(f32[10]{0} %p0), calls=%async_wrapped.0 %async-update = ((f32[10]{0}), f32[20]{0}, s32[]) async-update(((f32[10]{0}), f32[20]{0}, s32[]) %async-start) ROOT %async-done = f32[20]{0} async-done(((f32[10]{0}), f32[20]{0}, s32[]) %async-update), calls=%async_wrapped.1 } )"; EXPECT_THAT( ParseAndReturnUnverifiedModule(hlo_string).status(), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, HasSubstr("Expect async_wrapped_computation to be async_wrapped.0, " "but got async_wrapped.1"))); }
HloParserTest_AsyncDoneWrongDefaultThread
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AsyncDoneWrongDefaultThread) { const char* const hlo_string = R"( HloModule AsyncDoneWrongDefaultThread ENTRY %Entry (p0: f32[10]) -> f32[20] { %p0 = f32[10]{0} parameter(0) %async-start = ((f32[10]{0}), f32[20]{0}, s32[]) custom-call-start(f32[10]{0} %p0), custom_call_target="foo" %async-update = ((f32[10]{0}), f32[20]{0}, s32[]) custom-call-update(((f32[10]{0}), f32[20]{0}, s32[]) %async-start) ROOT %async-done = f32[20]{0} custom-call-done(((f32[10]{0}), f32[20]{0}, s32[]) %async-update), async_execution_thread="foo_thread" } )"; EXPECT_THAT(ParseAndReturnUnverifiedModule(hlo_string).status(), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, HasSubstr("Expect async_execution_thread to be main, " "but got foo_thread"))); }
HloParserTest_AsyncOpSharedComputation
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AsyncOpSharedComputation) { const char* const hlo_string = R"( HloModule AsyncOpSharedComputation %async_wrapped (async_param: f32[10]) -> f32[20] { %async_param = f32[10]{0} parameter(0) ROOT %call = f32[20]{0} custom-call(f32[10]{0} %async_param), custom_call_target="foo" } ENTRY %Entry (p0: f32[10]) -> f32[20] { %p0 = f32[10]{0} parameter(0) %async-start.0 = ((f32[10]{0}), f32[20]{0}, s32[]) async-start(f32[10]{0} %p0), calls=%async_wrapped %async-done.0 = f32[20]{0} async-done(((f32[10]{0}), f32[20]{0}, s32[]) %async-start.0) %async-start.1 = ((f32[10]{0}), f32[20]{0}, s32[]) async-start(f32[10]{0} %p0), calls=%async_wrapped ROOT %async-done.1 = f32[20]{0} async-done(((f32[10]{0}), f32[20]{0}, s32[]) %async-start.1) } )"; EXPECT_THAT(ParseAndReturnUnverifiedModule(hlo_string).status(), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, HasSubstr("Computation async_wrapped is already referenced " "by another async op"))); }
HloParserTest_AsyncOpTupleWrongType
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AsyncOpTupleWrongType) { const char* const hlo_string = R"( HloModule Module async_computation { p = f32[2,3] parameter(0) ROOT custom-call = f32[3,2] custom-call(p), custom_call_target="foo" } ENTRY AsyncStartAndAsyncDone { p0 = f32[2,3] parameter(0) async-start = ((f32[2,3])) async-start(p0), calls=async_computation ROOT async-done = f32[3,2] async-done(async-start), calls=async_computation } )"; EXPECT_THAT( ParseAndReturnUnverifiedModule(hlo_string).status(), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, HasSubstr("AsyncStart and AsyncUpdate expect the op shape to be " "in the form of " "((async-operands), async-outputs, state)."))); }
HloParserTest_AsyncStartMissingOperandWrapper
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AsyncStartMissingOperandWrapper) { const char* const hlo_string = R"( HloModule Module async_computation { p = f32[2,3] parameter(0) ROOT custom-call = f32[3,2] custom-call(p), custom_call_target="foo" } ENTRY AsyncStartMissingOperandWrapper { p0 = f32[2,3] parameter(0) async-start = (f32[2,3], f32[3,2], s32[]) async-start(p0), calls=async_computation async-update = ((f32[2,3]), f32[3,2], s32[]) async-update(async-start), calls=async_computation ROOT async-done = f32[3,2] async-done(async-update), calls=async_computation } )"; EXPECT_THAT( ParseAndReturnUnverifiedModule(hlo_string).status(), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, HasSubstr("AsyncStart and AsyncUpdate expect the op shape to be " "in the form of " "((async-operands), async-outputs, state)."))); }
HloParserTest_AsyncUpdateAndAsyncDoneNoAsyncStart
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AsyncUpdateAndAsyncDoneNoAsyncStart) { const char* const hlo_string = R"( HloModule Module ENTRY AsyncStartAndAsyncDone { p0 = f32[2,3] parameter(0) p1 = u32[] parameter(1) tuple = ((f32[2,3]), f32[2,3], u32[]) tuple(p0, p0, p1) async-update = ((f32[2,3]), f32[2,3], u32[]) custom-call-update(tuple) ROOT async-done = f32[2,3] custom-call-done(tuple) } )"; EXPECT_THAT( ParseAndReturnUnverifiedModule(hlo_string).status(), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, HasSubstr("AsyncUpdate and AsyncDone expect their operand to be " "the previous async op."))); }
HloParserTest_AsyncUpdateMissingOperandWrapper
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AsyncUpdateMissingOperandWrapper) { const char* const hlo_string = R"( HloModule Module async_computation { p = f32[2,3] parameter(0) ROOT custom-call = f32[3,2] custom-call(p), custom_call_target="foo" } ENTRY AsyncUpdateMissingOperandWrapper { p0 = f32[2,3] parameter(0) async-start = ((f32[2,3]), f32[3,2], s32[]) async-start(p0), calls=async_computation async-update = (f32[2,3], f32[3,2], s32[]) async-update(async-start), calls=async_computation ROOT async-done = f32[3,2] async-done(async-update), calls=async_computation } )"; EXPECT_THAT( ParseAndReturnUnverifiedModule(hlo_string).status(), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, HasSubstr("AsyncStart and AsyncUpdate expect the op shape to be " "in the form of " "((async-operands), async-outputs, state)."))); }
HloParserTest_AsyncUpdateWithSyntaxSugarWrongOp
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AsyncUpdateWithSyntaxSugarWrongOp) { const char* const hlo_string = R"( HloModule AsyncUpdateWithSyntaxSugarWrongOp ENTRY %Entry (p0: f32[10]) -> f32[20] { %p0 = f32[10]{0} parameter(0) %async-start = ((f32[10]{0}), f32[20]{0}, s32[]) custom-call-start(f32[10]{0} %p0), custom_call_target="foo" %async-update = ((f32[10]{0}), f32[20]{0}, s32[]) add-update(((f32[10]{0}), f32[20]{0}, s32[]) %async-start) ROOT %async-done = f32[20]{0} custom-call-done(((f32[10]{0}), f32[20]{0}, s32[]) %async-update) } )"; EXPECT_THAT(ParseAndReturnUnverifiedModule(hlo_string).status(), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, HasSubstr("Expect async wrapped opcode to be custom-call, " "but got add"))); }
HloParserTest_AsyncUpdateWrongComputation
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AsyncUpdateWrongComputation) { const char* const hlo_string = R"( HloModule AsyncUpdateWrongComputation %async_wrapped.0 (async_param: f32[10]) -> f32[20] { %async_param = f32[10]{0} parameter(0) ROOT %custom-call = f32[20]{0} custom-call(f32[10]{0} %async_param), custom_call_target="foo" } %async_wrapped.1 (async_param: f32[10]) -> f32[20] { %async_param = f32[10]{0} parameter(0) ROOT %custom-call = f32[20]{0} custom-call(f32[10]{0} %async_param), custom_call_target="foo" } ENTRY %Entry (p0: f32[10]) -> f32[20] { %p0 = f32[10]{0} parameter(0) %async-start = ((f32[10]{0}), f32[20]{0}, s32[]) async-start(f32[10]{0} %p0), calls=%async_wrapped.0 %async-update = ((f32[10]{0}), f32[20]{0}, s32[]) async-update(((f32[10]{0}), f32[20]{0}, s32[]) %async-start), calls=%async_wrapped.1 ROOT %async-done = f32[20]{0} async-done(((f32[10]{0}), f32[20]{0}, s32[]) %async-update) } )"; EXPECT_THAT( ParseAndReturnUnverifiedModule(hlo_string).status(), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, HasSubstr("Expect async_wrapped_computation to be async_wrapped.0, " "but got async_wrapped.1"))); }
HloParserTest_AsyncUpdateWrongDefaultThread
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AsyncUpdateWrongDefaultThread) { const char* const hlo_string = R"( HloModule AsyncUpdateWrongDefaultThread ENTRY %Entry (p0: f32[10]) -> f32[20] { %p0 = f32[10]{0} parameter(0) %async-start = ((f32[10]{0}), f32[20]{0}, s32[]) custom-call-start(f32[10]{0} %p0), custom_call_target="foo" %async-update = ((f32[10]{0}), f32[20]{0}, s32[]) custom-call-update(((f32[10]{0}), f32[20]{0}, s32[]) %async-start), async_execution_thread="foo_thread" ROOT %async-done = f32[20]{0} custom-call-done(((f32[10]{0}), f32[20]{0}, s32[]) %async-update) } )"; EXPECT_THAT(ParseAndReturnUnverifiedModule(hlo_string).status(), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, HasSubstr("Expect async_execution_thread to be main, " "but got foo_thread"))); }
HloParserTest_AttributesAnyOrder
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, AttributesAnyOrder) { const std::string original = R"(HloModule any_order_module ENTRY %Convolve1D1Window_0.v3 (input: f32[1,2,1], filter: f32[1,1,1]) -> f32[1,4,1] { %input = f32[1,2,1]{2,1,0} parameter(0) %copy = f32[1,2,1]{2,0,1} copy(f32[1,2,1]{2,1,0} %input) %filter = f32[1,1,1]{2,1,0} parameter(1) ROOT %convolution = f32[1,4,1]{2,0,1} convolution(f32[1,2,1]{2,0,1} %copy, f32[1,1,1]{2,1,0} %filter), feature_group_count=1, sharding={maximal device=1}, backend_config="foo", dim_labels=b0f_0io->b0f, window={pad=1_1 size=1} } )"; TF_EXPECT_OK(ParseAndReturnVerifiedModule(original).status()); }
HloParserTest_BufferDonorShapeIndexNotNumerical
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, BufferDonorShapeIndexNotNumerical) { const std::string original = R"( HloModule Module, buffer_donor={ (0, {0, a}), (0, {1}) } ENTRY entry { %p = (f32[], f32[]) parameter(0) %p0 = f32[] get-tuple-element((f32[], f32[]) %p), index=0 %p1 = f32[] get-tuple-element((f32[], f32[]) %p), index=1 ROOT %out = (f32[], f32[]) tuple(%p0, %p1) } )"; ExpectHasSubstr(ParseAndReturnUnverifiedModule(original).status().message(), "expects integer"); }
HloParserTest_BufferDonorWrongFormatAlphaParam
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, BufferDonorWrongFormatAlphaParam) { const std::string original = R"( HloModule Module, buffer_donor={ (zero, {0}), (0, {1}) } ENTRY entry { %p = (f32[], f32[]) parameter(0) %p0 = f32[] get-tuple-element((f32[], f32[]) %p), index=0 %p1 = f32[] get-tuple-element((f32[], f32[]) %p), index=1 ROOT %out = (f32[], f32[]) tuple(%p0, %p1) } )"; ExpectHasSubstr(ParseAndReturnUnverifiedModule(original).status().message(), "expects integer"); }
HloParserTest_CheckAliasPassthroughParams
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, CheckAliasPassthroughParams) { const char* const hlo_string = R"( HloModule TestModule, alias_passthrough_params=true ENTRY TestComputation { p0 = f16[2048,1024] parameter(0) p1 = f16[2048,1024] parameter(1) ROOT root = (f16[2048,1024], f16[2048,1024]) tuple(p0, p1) } )"; auto result = ParseAndReturnVerifiedModule(hlo_string); TF_EXPECT_OK(result.status()); EXPECT_TRUE(result.value()->config().alias_passthrough_params()); }
HloParserTest_CheckAllowSpmdShardingPropagationToOutput
xla/service/hlo_parser_test.cc
HloSchedule ScheduleFromInstructionOrder(HloModule* module) { HloSchedule schedule(module); for (HloComputation* computation : module->computations()) { if (!computation->IsFusionComputation()) { for (HloInstruction* instruction : computation->instructions()) { schedule.GetOrCreateSequence(computation).push_back(instruction); } } } return schedule; } bool CanInferShape(HloOpcode code) { switch (code) { case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAtan2: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCeil: case HloOpcode::kCholesky: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConvolution: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDivide: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFft: case HloOpcode::kFloor: case HloOpcode::kGather: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: case HloOpcode::kGetTupleElement: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kAnd: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kMap: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kPad: case HloOpcode::kPartitionId: case HloOpcode::kPopulationCount: case HloOpcode::kPower: case HloOpcode::kReal: case HloOpcode::kReduce: case HloOpcode::kRemainder: case HloOpcode::kReplicaId: case HloOpcode::kReverse: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kScatter: case HloOpcode::kSelect: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kReduceWindow: case HloOpcode::kSelectAndScatter: case HloOpcode::kSort: case HloOpcode::kSubtract: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kTopK: return true; // Technically the following ops do not require an explicit result shape, // but we made it so that we always write the shapes explicitly. case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDynamicReshape: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduceScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kSlice: // The following ops require an explicit result shape. case HloOpcode::kBitcast: case HloOpcode::kBitcastConvert: case HloOpcode::kConstant: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kFusion: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kReducePrecision: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngBitGenerator: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kStochasticConvert: return false; } } explicit HloParserImpl(absl::string_view str) : lexer_(str) {} ~Scope() { scoped_name_tables_->pop_back(); } bool SplitToInt64s(absl::string_view s, char delim, std::vector<int64_t>* out) { for (const auto& split : absl::StrSplit(s, delim)) { int64_t val; if (!absl::SimpleAtoi(split, &val)) { return false; } out->push_back(val); } return true; } std::vector<ReplicaGroup> CreateReplicaGroups( absl::Span<const std::vector<int64_t>> groups) { std::vector<ReplicaGroup> replica_groups; absl::c_transform(groups, std::back_inserter(replica_groups), [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); return replica_groups; } [](const std::vector<int64_t>& ids) { ReplicaGroup group; *group.mutable_replica_ids() = {ids.begin(), ids.end()}; return group; }); bool HloParserImpl::Error(LocTy loc, absl::string_view msg) { auto line_col = lexer_.GetLineAndColumn(loc); const unsigned line = line_col.first; const unsigned col = line_col.second; std::vector<std::string> error_lines; error_lines.push_back( StrCat("was parsing ", line, ":", col, ": error: ", msg)); error_lines.emplace_back(lexer_.GetLine(loc)); error_lines.push_back(col == 0 ? "" : StrCat(std::string(col - 1, ' '), "^")); error_.push_back(StrJoin(error_lines, "\n")); VLOG(1) << "Error: " << error_.back(); return false; } VLOG(1) << "Error: " << error_.back(); absl::Status HloParserImpl::Run(HloModule* module) { lexer_.Lex(); if ((lexer_.GetKind() == TokKind::kw_HloModule) || (lexer_.GetKind() == TokKind::kw_ENTRY) || (lexer_.LookAhead() == TokKind::kLbrace)) { // This means that the text contains a full HLO module. bool parse_module_without_header = (lexer_.GetKind() == TokKind::kw_HloModule) ? false : true; if (!ParseHloModule(module, parse_module_without_header)) { return InvalidArgument( "Syntax error when trying to parse the text as a HloModule:\n%s", GetError()); } return absl::OkStatus(); } // This means that the text is a single HLO instruction. if (!ParseSingleInstruction(module)) { return InvalidArgument( "Syntax error when trying to parse the text as a single " "HloInstruction:\n%s", GetError()); } return absl::OkStatus(); } HloParserImpl::FindInstruction(const std::string& name, const optional<Shape>& shape) { std::pair<HloInstruction*, LocTy>* instr = nullptr; if (!name.empty()) { instr = tsl::gtl::FindOrNull(current_name_table(), name); } // Potentially call the missing instruction hook. if (instr == nullptr && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { if (!shape.has_value()) { Error(lexer_.GetLoc(), "Operand had no shape in HLO text; cannot create parameter for " "single-instruction module."); return nullptr; } return create_missing_instruction_(name, *shape); } if (instr != nullptr && shape.has_value() && !ShapeUtil::Compatible(instr->first->shape(), shape.value())) { Error( lexer_.GetLoc(), StrCat("The declared operand shape ", ShapeUtil::HumanStringWithLayout(shape.value()), " is not compatible with the shape of the operand instruction ", ShapeUtil::HumanStringWithLayout(instr->first->shape()), ".")); return nullptr; } return instr; } bool HloParserImpl::ParseShapeIndex(ShapeIndex* out) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of ShapeIndex")) { return false; } std::vector<int64_t> idxs; while (lexer_.GetKind() != TokKind::kRbrace) { int64_t idx; if (!ParseInt64(&idx)) { return false; } idxs.push_back(idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of ShapeIndex")) { return false; } *out = ShapeIndex(idxs.begin(), idxs.end()); return true; } bool HloParserImpl::ParseAliasing(AliasingData* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<input_param>, " "<input_param_shape_index>) OR <output_shape_index>: <input_param>"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } HloInputOutputAliasConfig::AliasKind alias_kind = HloInputOutputAliasConfig::kMayAlias; if (EatIfPresent(TokKind::kComma)) { std::string type; ParseName(&type); if (type == "must-alias") { alias_kind = HloInputOutputAliasConfig::kMustAlias; } else if (type == "may-alias") { alias_kind = HloInputOutputAliasConfig::kMayAlias; } else { return TokenError("Unexpected aliasing kind; expected SYSTEM or USER"); } } data->emplace(std::piecewise_construct, std::forward_as_tuple(out), std::forward_as_tuple(param_num, param_idx, alias_kind)); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of aliasing description")) { return false; } return true; } bool HloParserImpl::ParseBufferDonor(BufferDonor* data) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of buffer donor description")) { return false; } std::string errmsg = "Expected format: (<input_param>, <input_param_shape_index>)"; while (lexer_.GetKind() != TokKind::kRbrace) { if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t param_num; ParseInt64(&param_num); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex param_idx; if (!ParseShapeIndex(&param_idx)) { return false; } if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } data->emplace(param_num, param_idx); if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of buffer donor description")) { return false; } return true; } bool HloParserImpl::ParseComputationLayout( ComputationLayout* computation_layout) { if (!ParseToken(TokKind::kLbrace, "Expects '{' at the start of aliasing description")) { return false; } if (!ParseToken(TokKind::kLparen, "Expects ( before parameter shape list")) { return false; } while (lexer_.GetKind() != TokKind::kRparen) { Shape param; if (!ParseShape(&param)) { return false; } computation_layout->add_parameter_layout(ShapeLayout(param)); if (lexer_.GetKind() == TokKind::kRparen) { break; } if (!ParseToken(TokKind::kComma, "Expects , between parameter shapes")) { return false; } } if (!ParseToken(TokKind::kRparen, "Expects ) at end of parameter shape list")) { return false; } if (!ParseToken(TokKind::kArrow, "Expects -> before result shape")) { return false; } Shape result; if (!ParseShape(&result)) { return false; } *computation_layout->mutable_result_layout() = ShapeLayout(result); if (!ParseToken(TokKind::kRbrace, "Expects '}' at the end of computation layouts")) { return false; } return true; } bool HloParserImpl::ParseInstructionOutputOperandAliasing( std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>* aliasing_output_operand_pairs) { if (!ParseToken( TokKind::kLbrace, "Expects '{' at the start of instruction aliasing description")) { return false; } while (lexer_.GetKind() != TokKind::kRbrace) { ShapeIndex out; if (!ParseShapeIndex(&out)) { return false; } std::string errmsg = "Expected format: <output_shape_index>: (<operand_index>, " "<operand_shape_index>)"; if (!ParseToken(TokKind::kColon, errmsg)) { return false; } if (!ParseToken(TokKind::kLparen, errmsg)) { return false; } int64_t operand_index; ParseInt64(&operand_index); if (!ParseToken(TokKind::kComma, errmsg)) { return false; } ShapeIndex operand_shape_index; if (!ParseShapeIndex(&operand_shape_index)) { return false; } aliasing_output_operand_pairs->emplace_back( out, std::pair<int64_t, ShapeIndex>{operand_index, operand_shape_index}); if (!ParseToken(TokKind::kRparen, errmsg)) { return false; } if (!EatIfPresent(TokKind::kComma)) { break; } } if (!ParseToken( TokKind::kRbrace, "Expects '}' at the end of instruction aliasing description")) { return false; } return true; } bool HloParserImpl::ParseCustomCallSchedule(CustomCallSchedule* result) { VLOG(3) << "ParseCustomCallSchedule"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call schedule"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallSchedule(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call schedule but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallSchedule"; bool HloParserImpl::ParseCustomCallApiVersion(CustomCallApiVersion* result) { VLOG(3) << "ParseCustomCallApiVersion"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects custom-call API version"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToCustomCallApiVersion(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects custom-call API version but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseCustomCallApiVersion"; bool HloParserImpl::ParseSparsityDescriptor( std::vector<SparsityDescriptor>* result) { VLOG(3) << "ParseSparsityDescriptor"; if (lexer_.GetKind() != TokKind::kSparsityDesc) { return TokenError("expects sparsity descriptor, e.g. L.0@2:4"); } std::string val = lexer_.GetStrVal(); std::vector<absl::string_view> split = absl::StrSplit(val, '_'); for (absl::string_view item : split) { std::vector<absl::string_view> splitA = absl::StrSplit(item, '@'); std::vector<absl::string_view> splitB = absl::StrSplit(splitA[0], '.'); std::vector<absl::string_view> splitC = absl::StrSplit(splitA[1], ':'); SparsityDescriptor descriptor; int dim, n, m; if (!absl::SimpleAtoi(splitB[1], &dim) || dim < 0) { return TokenError("Invalid dimension number"); } if (!absl::SimpleAtoi(splitC[0], &n) || !absl::SimpleAtoi(splitC[1], &m) || n < 1 || m <= n) { return TokenError("Invalid structured sparsity type"); } descriptor.set_type(SparsityType::SPARSITY_STRUCTURED_N_M); descriptor.set_index(splitB[0] == "L" ? 0 : 1); descriptor.set_dimension(dim); descriptor.set_n(n); descriptor.set_m(m); result->push_back(descriptor); } lexer_.Lex(); return true; } VLOG(3) << "ParseSparsityDescriptor"; bool HloParserImpl::ParseHloModule(HloModule* module, bool parse_module_without_header) { std::string name; std::optional<bool> is_scheduled; std::optional<int64_t> replica_count; std::optional<int64_t> num_partitions; std::optional<AliasingData> aliasing_data; std::optional<BufferDonor> buffer_donor_data; std::optional<bool> alias_passthrough_params; absl::flat_hash_map<std::string, AttrConfig> attrs; std::optional<ComputationLayout> entry_computation_layout; std::optional<FrontendAttributes> frontend_attributes; BoolList allow_spmd_sharding_propagation_to_parameters; BoolList allow_spmd_sharding_propagation_to_output; attrs["is_scheduled"] = {/*required=*/false, AttrTy::kBool, &is_scheduled}; attrs["replica_count"] = {/*required=*/false, AttrTy::kInt64, &replica_count}; attrs["num_partitions"] = {/*required=*/false, AttrTy::kInt64, &num_partitions}; attrs["input_output_alias"] = {/*required=*/false, AttrTy::kAliasing, &aliasing_data}; attrs["buffer_donor"] = {/*required=*/false, AttrTy::kBufferDonor, &buffer_donor_data}; attrs["alias_passthrough_params"] = {/*required=*/false, AttrTy::kBool, &alias_passthrough_params}; attrs["entry_computation_layout"] = {/*required=*/false, AttrTy::kComputationLayout, &entry_computation_layout}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["allow_spmd_sharding_propagation_to_parameters"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_parameters}; attrs["allow_spmd_sharding_propagation_to_output"] = { /*required=*/false, AttrTy::kBracedBoolListOrBool, &allow_spmd_sharding_propagation_to_output}; if (!parse_module_without_header) { if (lexer_.GetKind() != TokKind::kw_HloModule) { return TokenError("expects HloModule"); } // Eat 'HloModule' lexer_.Lex(); if (!ParseName(&name)) { return false; } if (!ParseAttributes(attrs)) { return false; } module->set_name(name); } if (!ParseComputations(module)) { return false; } if (parse_module_without_header) { name = absl::StrCat("module_", module->entry_computation()->name()); entry_computation_layout = ComputationLayout(module->entry_computation()->ComputeProgramShape(), /*ignore_layouts*/ false); } module->set_name(name); if (is_scheduled.value_or(false)) { TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); } HloModuleConfig config = module->config(); bool default_config = true; if (alias_passthrough_params.value_or(false)) { config.set_alias_passthrough_params(true); default_config = false; } if (num_partitions.value_or(1) != 1) { config.set_num_partitions(*num_partitions); config.set_use_spmd_partitioning(true); default_config = false; } if (replica_count.value_or(1) != 1) { config.set_replica_count(*replica_count); default_config = false; } if (entry_computation_layout.has_value()) { *config.mutable_entry_computation_layout() = *entry_computation_layout; default_config = false; } if (frontend_attributes) { module->set_frontend_attributes(frontend_attributes.value()); } if (!allow_spmd_sharding_propagation_to_parameters.empty()) { config.set_allow_spmd_sharding_propagation_to_parameters( allow_spmd_sharding_propagation_to_parameters); default_config = false; } if (!allow_spmd_sharding_propagation_to_output.empty()) { config.set_allow_spmd_sharding_propagation_to_output( allow_spmd_sharding_propagation_to_output); default_config = false; } if (!default_config) { module->set_config(config); } if (aliasing_data) { HloInputOutputAliasConfig alias_config(module->result_shape()); for (auto& p : *aliasing_data) { absl::Status st = alias_config.SetUpAlias(p.first, p.second.parameter_number, p.second.parameter_index, p.second.kind); if (!st.ok()) { return TokenError(st.message()); } } module->input_output_alias_config() = alias_config; } if (buffer_donor_data) { HloBufferDonorConfig buffer_donor_config; for (auto& p : *buffer_donor_data) { absl::Status st = buffer_donor_config.AddBufferDonor(p.param_number, p.param_index); if (!st.ok()) { return TokenError(st.message()); } } module->buffer_donor_config() = buffer_donor_config; } return true; } bool HloParserImpl::ParseComputations(HloModule* module) { HloComputation* entry_computation = nullptr; do { if (!ParseComputation(&entry_computation)) { return false; } } while (lexer_.GetKind() != TokKind::kEof); for (int i = 0; i < computations_.size(); i++) { // If entry_computation is not nullptr, it means the computation it pointed // to is marked with "ENTRY"; otherwise, no computation is marked with // "ENTRY", and we use the last computation as the entry computation. We // add the non-entry computations as embedded computations to the module. if ((entry_computation != nullptr && computations_[i].get() != entry_computation) || (entry_computation == nullptr && i != computations_.size() - 1)) { module->AddEmbeddedComputation(std::move(computations_[i])); continue; } auto computation = module->AddEntryComputation(std::move(computations_[i])); // The parameters and result layouts were set to default layout. Here we // set the layouts to what the hlo text says. for (int p = 0; p < computation->num_parameters(); p++) { const Shape& param_shape = computation->parameter_instruction(p)->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_parameter_layout(p) ->CopyLayoutFromShape(param_shape)); } const Shape& result_shape = computation->root_instruction()->shape(); TF_CHECK_OK(module->mutable_entry_computation_layout() ->mutable_result_layout() ->CopyLayoutFromShape(result_shape)); } return true; } bool HloParserImpl::ParseComputation(HloComputation** entry_computation) { LocTy maybe_entry_loc = lexer_.GetLoc(); const bool is_entry_computation = EatIfPresent(TokKind::kw_ENTRY); std::string name; LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name)) { return false; } LocTy shape_loc = nullptr; Shape shape; if (CanBeParamListToShape() && !ParseParamListToShape(&shape, &shape_loc)) { return false; } HloComputation* computation = nullptr; if (!ParseInstructionList(&computation, name)) { return false; } // If param_list_to_shape was present, check compatibility. if (shape_loc != nullptr && !ShapeUtil::Compatible(computation->root_instruction()->shape(), shape)) { return Error( shape_loc, StrCat( "Shape of computation ", name, ", ", ShapeUtil::HumanString(shape), ", is not compatible with that of its root instruction ", computation->root_instruction()->name(), ", ", ShapeUtil::HumanString(computation->root_instruction()->shape()))); } absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> execution_thread = HloInstruction::kMainExecutionThread; attrs["execution_thread"] = {/*required=*/false, AttrTy::kString, &execution_thread}; if (!ParseAttributes(attrs)) { return false; } computation->SetExecutionThread(*execution_thread); if (is_entry_computation) { if (*entry_computation != nullptr) { return Error(maybe_entry_loc, "expects only one ENTRY"); } *entry_computation = computation; } return AddComputation(name, computation, name_loc); } bool HloParserImpl::ParseInstructionList(HloComputation** computation, const std::string& computation_name) { Scope scope(&scoped_name_tables_); HloComputation::Builder builder(computation_name); if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction list.")) { return false; } std::string root_name; do { if (!ParseInstruction(&builder, &root_name)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); if (!ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction list.")) { return false; } HloInstruction* root = nullptr; if (!root_name.empty()) { std::pair<HloInstruction*, LocTy>* root_node = tsl::gtl::FindOrNull(current_name_table(), root_name); // This means some instruction was marked as ROOT but we didn't find it in // the pool, which should not happen. if (root_node == nullptr) { // LOG(FATAL) crashes the program by calling abort(). LOG(FATAL) << "instruction " << root_name << " was marked as ROOT but the parser has not seen it before"; } root = root_node->first; } // Now root can be either an existing instruction or a nullptr. If it's a // nullptr, the implementation of Builder will set the last instruction as // the root instruction. computations_.emplace_back(builder.Build(root)); *computation = computations_.back().get(); return true; } bool HloParserImpl::ParseInstruction(HloComputation::Builder* builder, std::string* root_name) { std::string name; LocTy maybe_root_loc = lexer_.GetLoc(); bool is_root = EatIfPresent(TokKind::kw_ROOT); const LocTy name_loc = lexer_.GetLoc(); if (!ParseName(&name) || !ParseToken(TokKind::kEqual, "expects '=' in instruction")) { return false; } if (is_root) { if (!root_name->empty()) { return Error(maybe_root_loc, "one computation should have only one ROOT"); } *root_name = name; } return ParseInstructionRhs(builder, name, name_loc); } bool HloParserImpl::ParseInstructionRhs(HloComputation::Builder* builder, std::string name, LocTy name_loc, bool allow_attributes) { Shape shape; HloOpcode opcode; std::optional<HloOpcode> async_wrapped_opcode; std::vector<HloInstruction*> operands; const bool parse_shape = CanBeShape(); if ((parse_shape && !ParseShape(&shape)) || !ParseOpcode(&opcode, &async_wrapped_opcode)) { return false; } if (!parse_shape && !CanInferShape(opcode)) { return TokenError(StrFormat("cannot infer shape for opcode: %s", HloOpcodeString(opcode))); } // Add optional attributes. These are added to any HloInstruction type if // present. absl::flat_hash_map<std::string, AttrConfig> attrs; optional<OpSharding> sharding; optional<FrontendAttributes> frontend_attributes; optional<StatisticsViz> statistics_viz; attrs["sharding"] = {/*required=*/false, AttrTy::kSharding, &sharding}; attrs["frontend_attributes"] = { /*required=*/false, AttrTy::kFrontendAttributes, &frontend_attributes}; attrs["statistics"] = {/*required=*/false, AttrTy::kStatisticsViz, &statistics_viz}; optional<ParameterReplication> parameter_replication; attrs["parameter_replication"] = {/*required=*/false, AttrTy::kParameterReplication, &parameter_replication}; optional<std::vector<HloInstruction*>> predecessors; attrs["control-predecessors"] = {/*required=*/false, AttrTy::kInstructionList, &predecessors}; optional<OpMetadata> metadata; attrs["metadata"] = {/*required=*/false, AttrTy::kMetadata, &metadata}; optional<std::string> backend_config; attrs["backend_config"] = {/*required=*/false, AttrTy::kStringOrJsonDict, &backend_config}; std::optional<Shape> maybe_shape; if (parse_shape) { maybe_shape = shape; } HloInstruction* instruction = CreateInstruction(builder, name, maybe_shape, opcode, async_wrapped_opcode, attrs, allow_attributes); if (instruction == nullptr) { return false; } // Generate a unique name if the name is empty. This is used for nested // instructions (e.g. the `max` in add(max(x, y), z)). // // Otherwise, register the given name with the name uniquer. if (name.empty()) { name = name_uniquer_.GetUniqueName( absl::StrCat(HloOpcodeString(instruction->opcode()), ".anon")); } else { name_uniquer_.GetUniqueName(name); } instruction->SetAndSanitizeName(name); if (instruction->name() != name) { return Error(name_loc, StrCat("illegal instruction name: ", name, "; suggest renaming to: ", instruction->name())); } // Add shared attributes like metadata to the instruction, if they were seen. if (sharding) { // TODO(b/257495070): Eliminate tuple sharding normalization in HLO parser. // Allow existing HLO text with invalid sharding on tuple shapes by // normalizing tuple sharding. HloSharding hlo_sharding = HloSharding::FromProto(sharding.value()).value(); hlo_sharding = hlo_sharding.NormalizeTupleSharding(instruction->shape()); instruction->set_sharding(std::move(hlo_sharding)); } if (parameter_replication) { int leaf_count = ShapeUtil::GetLeafCount(instruction->shape()); const auto& replicated = parameter_replication->replicated_at_leaf_buffers(); if (leaf_count != replicated.size()) { return Error(lexer_.GetLoc(), StrCat("parameter has ", leaf_count, " leaf buffers, but parameter_replication has ", replicated.size(), " elements.")); } instruction->set_parameter_replicated_at_leaf_buffers(replicated); } if (predecessors) { for (auto* pre : *predecessors) { absl::Status status = pre->AddControlDependencyTo(instruction); if (!status.ok()) { return Error(name_loc, StrCat("error adding control dependency for: ", name, " status: ", status.ToString())); } } } if (metadata) { instruction->set_metadata(*metadata); } if (backend_config) { instruction->set_raw_backend_config_string(std::move(*backend_config)); } if (frontend_attributes) { instruction->set_frontend_attributes(*frontend_attributes); } if (statistics_viz) { instruction->set_statistics_viz(*statistics_viz); } return AddInstruction(name, instruction, name_loc); } HloInstruction* HloParserImpl::CreateInstruction( // NOLINT HloComputation::Builder* builder, absl::string_view name, std::optional<Shape> shape, HloOpcode opcode, std::optional<HloOpcode> async_wrapped_opcode, absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes, std::vector<HloInstruction*>* preset_operands) { std::vector<HloInstruction*> operands; if (preset_operands) { operands = *preset_operands; } const auto maybe_infer_shape = [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; switch (opcode) { case HloOpcode::kParameter: { int64_t parameter_number; if (!ParseToken(TokKind::kLparen, "expects '(' before parameter number") || !ParseInt64(&parameter_number)) { return nullptr; } const LocTy loc = lexer_.GetLoc(); if (parameter_number < 0) { Error(loc, "parameter number must be >= 0"); return nullptr; } if (!ParseToken(TokKind::kRparen, "expects ')' after parameter number") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::string param_name(name); auto result = builder->AddParameter(HloInstruction::CreateParameter( parameter_number, *shape, param_name)); if (!result.ok()) { Error(loc, result.status().message()); return nullptr; } return result.value(); } case HloOpcode::kConstant: { Literal literal; if (!ParseToken(TokKind::kLparen, "expects '(' before constant literal") || !ParseLiteral(&literal, *shape) || !ParseToken(TokKind::kRparen, "expects ')' after constant literal") || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); } case HloOpcode::kIota: { optional<int64_t> iota_dimension; attrs["iota_dimension"] = {/*required=*/true, AttrTy::kInt64, &iota_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateIota(*shape, *iota_dimension)); } case HloOpcode::kTopK: { optional<int64_t> k; attrs["k"] = {/*required=*/true, AttrTy::kInt64, &k}; optional<bool> largest; attrs["largest"] = {/*required=*/false, AttrTy::kBool, &largest}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTopK( *shape, operands[0], *k, (largest.has_value() ? *largest : true))); } // Unary ops. case HloOpcode::kAbs: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceDone: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kBitcast: case HloOpcode::kCeil: case HloOpcode::kClz: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCopy: case HloOpcode::kCopyDone: case HloOpcode::kCos: case HloOpcode::kOptimizationBarrier: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kFloor: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kNot: case HloOpcode::kNegate: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kRsqrt: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kTan: case HloOpcode::kTanh: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateUnary(*shape, opcode, operands[0])); } // Binary ops. case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kMultiply: case HloOpcode::kSubtract: case HloOpcode::kAtan2: case HloOpcode::kComplex: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kAnd: case HloOpcode::kOr: case HloOpcode::kXor: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: case HloOpcode::kStochasticConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBinary( *shape, opcode, operands[0], operands[1])); } // Ternary ops. case HloOpcode::kClamp: case HloOpcode::kSelect: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTernary( *shape, opcode, operands[0], operands[1], operands[2])); } // Other supported ops. case HloOpcode::kConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateConvert(*shape, operands[0])); } case HloOpcode::kBitcastConvert: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateBitcastConvert(*shape, operands[0])); } case HloOpcode::kAllGather: case HloOpcode::kAllGatherStart: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<std::vector<int64_t>> dimensions; optional<bool> constrain_layout; optional<bool> use_global_device_ids; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllGather) { return builder->AddInstruction(HloInstruction::CreateAllGather( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } return builder->AddInstruction(HloInstruction::CreateAllGatherStart( *shape, operands, dimensions->at(0), device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllReduce: case HloOpcode::kAllReduceStart: case HloOpcode::kReduceScatter: { optional<std::vector<std::vector<int64_t>>> tmp_groups; optional<HloComputation*> to_apply; optional<std::vector<int64_t>> replica_group_ids; optional<int64_t> channel_id; optional<bool> constrain_layout; optional<bool> use_global_device_ids; optional<std::vector<int64_t>> dimensions; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; attrs["use_global_device_ids"] = {/*required=*/false, AttrTy::kBool, &use_global_device_ids}; if (opcode == HloOpcode::kReduceScatter) { attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; } if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } CollectiveDeviceList device_list(replica_groups); if (opcode == HloOpcode::kAllReduce) { return builder->AddInstruction(HloInstruction::CreateAllReduce( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } else if (opcode == HloOpcode::kReduceScatter) { return builder->AddInstruction(HloInstruction::CreateReduceScatter( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false, dimensions->at(0))); } return builder->AddInstruction(HloInstruction::CreateAllReduceStart( *shape, operands, *to_apply, device_list, constrain_layout ? *constrain_layout : false, channel_id, use_global_device_ids ? *use_global_device_ids : false)); } case HloOpcode::kAllToAll: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; optional<bool> constrain_layout; attrs["constrain_layout"] = {/*required=*/false, AttrTy::kBool, &constrain_layout}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || (dimensions && dimensions->size() != 1)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } optional<int64_t> split_dimension; if (dimensions) { split_dimension = dimensions->at(0); } return builder->AddInstruction(HloInstruction::CreateAllToAll( *shape, operands, CollectiveDeviceList(replica_groups), constrain_layout ? *constrain_layout : false, channel_id, split_dimension)); } case HloOpcode::kCollectiveBroadcast: { optional<std::vector<std::vector<int64_t>>> tmp_groups; attrs["replica_groups"] = {/*required=*/true, AttrTy::kBracedInt64ListList, &tmp_groups}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<ReplicaGroup> replica_groups; if (tmp_groups) { replica_groups = CreateReplicaGroups(*tmp_groups); } return builder->AddInstruction(HloInstruction::CreateCollectiveBroadcast( *shape, operands, CollectiveDeviceList(replica_groups), false, channel_id)); } case HloOpcode::kCollectivePermute: case HloOpcode::kCollectivePermuteStart: { optional<std::vector<std::vector<int64_t>>> source_targets; attrs["source_target_pairs"] = { /*required=*/true, AttrTy::kBracedInt64ListList, &source_targets}; optional<int64_t> channel_id; attrs["channel_id"] = {/*required=*/false, AttrTy::kInt64, &channel_id}; optional<std::vector<std::vector<int64_t>>> slice_sizes; attrs["slice_sizes"] = {/*required=*/false, AttrTy::kBracedInt64ListList, &slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } std::vector<std::pair<int64_t, int64_t>> pairs(source_targets->size()); for (int i = 0; i < pairs.size(); i++) { if ((*source_targets)[i].size() != 2) { TokenError("expects 'source_target_pairs=' to be a list of pairs"); return nullptr; } pairs[i].first = (*source_targets)[i][0]; pairs[i].second = (*source_targets)[i][1]; } if (!slice_sizes.has_value()) { if (operands.size() != 1) { TokenError( "CollectivePermute and CollectivePermuteStart must have exactly " "one operand (input buffer) unless it performs dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction( HloInstruction::CreateCollectivePermute(*shape, operands[0], pairs, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart(*shape, operands[0], pairs, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } if (operands.size() != 4) { TokenError( "CollectivePermute and CollectivePermuteStart must " "have exactly four operands for dynamic-slice and " "in-place update."); return nullptr; } if (opcode == HloOpcode::kCollectivePermute) { return builder->AddInstruction(HloInstruction::CreateCollectivePermute( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } if (opcode == HloOpcode::kCollectivePermuteStart) { return builder->AddInstruction( HloInstruction::CreateCollectivePermuteStart( *shape, operands[0], operands[1], operands[2], operands[3], pairs, *slice_sizes, channel_id)); } LOG(FATAL) << "Expect opcode to be CollectivePermute or " "CollectivePermuteStart, but got " << opcode; } case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: { std::optional<HloComputation*> async_computation; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; // Verify operand/resulting shapes if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } } if (opcode == HloOpcode::kAsyncStart || opcode == HloOpcode::kAsyncUpdate) { if (!is_async_shape_correct(*shape)) { TokenError( "AsyncStart and AsyncUpdate expect the op shape to be in the " "form of " "((async-operands), async-outputs, state)."); return nullptr; } } // async-{update,done} expect their one singular operand to be the // previous async op. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (operands.size() != 1 || !is_async_shape_correct(operands[0]->shape())) { TokenError( "AsyncUpdate and AsyncDone expect a single operand in the form " "of ((async-operands), async-outputs, state)."); return nullptr; } if (!operands[0]->IsAsynchronous()) { TokenError( "AsyncUpdate and AsyncDone expect their operand to be the " "previous async op."); return nullptr; } } optional<std::string> async_execution_thread; attrs["async_execution_thread"] = {/*required=*/false, AttrTy::kString, &async_execution_thread}; if (async_wrapped_opcode) { // Only generate async-wrapper for async-start. if (opcode == HloOpcode::kAsyncStart) { std::vector<HloInstruction*> async_wrapped_operands; std::vector<Shape> async_wrapped_operand_shapes; Shape async_wrapped_root_shape; for (const HloInstruction* operand : operands) { async_wrapped_operand_shapes.push_back(operand->shape()); } async_wrapped_root_shape = shape->tuple_shapes(1); HloComputation::Builder async_wrapped_builder("async_wrapped"); async_wrapped_operands.reserve(async_wrapped_operand_shapes.size()); for (int i = 0; i < async_wrapped_operand_shapes.size(); ++i) { async_wrapped_operands.push_back( async_wrapped_builder.AddInstruction( HloInstruction::CreateParameter( i, async_wrapped_operand_shapes.at(i), "async_param"))); } HloInstruction* root = CreateInstruction(&async_wrapped_builder, "async_op", async_wrapped_root_shape, *async_wrapped_opcode, /*async_wrapped_opcode=*/std::nullopt, attrs, allow_attributes, &async_wrapped_operands); if (!root) { return nullptr; } computations_.emplace_back(async_wrapped_builder.Build(root)); async_computation = computations_.back().get(); } else { // Since async-{update,done} will inherit the computation from // async-start, we'll only need to make sure it matches what was // specified explicitily. if (operands[0]->async_wrapped_opcode() != *async_wrapped_opcode) { TokenError( StrFormat("Expect async wrapped opcode to be %s, but got %s", HloOpcodeString(operands[0]->async_wrapped_opcode()), HloOpcodeString(*async_wrapped_opcode))); return nullptr; } } } else { attrs["calls"] = {/*required=*/opcode == HloOpcode::kAsyncStart, AttrTy::kHloComputation, &async_computation}; } // Attributes would have already been consumed when constructing the // async wrapped computation for async-start. if (!(async_wrapped_opcode && opcode == HloOpcode::kAsyncStart)) { if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } } // Async attributes on async-{update,done} are allowed for backward // compatibility reasons, but are ignored, since they are inherited // from the async-start op. Simply check that whatever is explicitly // specified matches what is inherited. if (opcode == HloOpcode::kAsyncUpdate || opcode == HloOpcode::kAsyncDone) { if (async_execution_thread && operands[0]->async_execution_thread() != *async_execution_thread) { TokenError(StrFormat( "Expect async_execution_thread to be %s, but got %s", operands[0]->async_execution_thread(), *async_execution_thread)); return nullptr; } if (async_computation && operands[0]->async_wrapped_computation() != *async_computation) { TokenError( StrFormat("Expect async_wrapped_computation to be %s, but got %s", operands[0]->async_wrapped_computation()->name(), (*async_computation)->name())); return nullptr; } } // There should be a 1:1 correspondence between async-start ops and // async wrapped computations. At this stage, the computation should // not be referenced by any other async op. if (opcode == HloOpcode::kAsyncStart && (*async_computation)->IsAsyncComputation()) { TokenError(StrFormat( "Computation %s is already referenced by another async op", (*async_computation)->name())); return nullptr; } if (opcode == HloOpcode::kAsyncStart) { // async_execution_thread only needs to be populated for async-start, // as the rest of the async chain will reference the root op. if (!async_execution_thread) { async_execution_thread = HloInstruction::kMainExecutionThread; } return builder->AddInstruction(HloInstruction::CreateAsyncStart( *shape, operands, *async_computation, *async_execution_thread)); } if (opcode == HloOpcode::kAsyncUpdate) { return builder->AddInstruction( HloInstruction::CreateAsyncUpdate(*shape, operands[0])); } return builder->AddInstruction( HloInstruction::CreateAsyncDone(*shape, operands[0])); } case HloOpcode::kCopyStart: { optional<int> cross_program_prefetch_index = std::nullopt; attrs["cross_program_prefetch_index"] = { /*required=*/false, AttrTy::kInt32, &cross_program_prefetch_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCopyStart( *shape, operands[0], cross_program_prefetch_index)); } case HloOpcode::kReplicaId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction(HloInstruction::CreateReplicaId(*shape)); } return builder->AddInstruction(HloInstruction::CreateReplicaId()); } case HloOpcode::kPartitionId: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (shape.has_value()) { return builder->AddInstruction( HloInstruction::CreatePartitionId(*shape)); } return builder->AddInstruction(HloInstruction::CreatePartitionId()); } case HloOpcode::kDynamicReshape: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicReshape( *shape, operands[0], absl::Span<HloInstruction* const>(operands).subspan(1))); } case HloOpcode::kReshape: { optional<int64_t> inferred_dimension; attrs["inferred_dimension"] = {/*required=*/false, AttrTy::kInt64, &inferred_dimension}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReshape( *shape, operands[0], inferred_dimension.value_or(-1))); } case HloOpcode::kAfterAll: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { return builder->AddInstruction(HloInstruction::CreateToken()); } return builder->AddInstruction(HloInstruction::CreateAfterAll(operands)); } case HloOpcode::kAddDependency: { if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateAddDependency(operands[0], operands[1])); } case HloOpcode::kSort: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; optional<bool> is_stable = false; attrs["is_stable"] = {/*required=*/false, AttrTy::kBool, &is_stable}; optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateSort(*shape, dimensions->at(0), operands, to_apply.value(), is_stable.value())); } case HloOpcode::kTuple: { if ((!preset_operands && !(shape.has_value() ? ParseOperands(&operands, builder, shape->tuple_shapes_size()) : ParseOperands(&operands, builder))) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { return nullptr; } // HloInstruction::CreateTuple() infers the shape of the tuple from // operands and should not be used here. return builder->AddInstruction( HloInstruction::CreateVariadic(*shape, HloOpcode::kTuple, operands)); } case HloOpcode::kWhile: { optional<HloComputation*> condition; optional<HloComputation*> body; attrs["condition"] = {/*required=*/true, AttrTy::kHloComputation, &condition}; attrs["body"] = {/*required=*/true, AttrTy::kHloComputation, &body}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateWhile( *shape, *condition, *body, /*init=*/operands[0])); } case HloOpcode::kRecv: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // If the is_host_transfer attribute is not present then default to false. return builder->AddInstruction(HloInstruction::CreateRecv( shape->tuple_shapes(0), operands[0], *channel_id, *is_host_transfer)); } case HloOpcode::kRecvDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateRecvDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kSend: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSend( operands[0], operands[1], *channel_id, *is_host_transfer)); } case HloOpcode::kSendDone: { optional<int64_t> channel_id; // If the is_host_transfer attribute is not present then default to false. optional<bool> is_host_transfer = false; attrs["channel_id"] = {/*required=*/true, AttrTy::kInt64, &channel_id}; attrs["is_host_transfer"] = {/*required=*/false, AttrTy::kBool, &is_host_transfer}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (dynamic_cast<const HloChannelInstruction*>(operands[0]) != nullptr) { if (channel_id != operands[0]->channel_id()) { return nullptr; } } return builder->AddInstruction(HloInstruction::CreateSendDone( operands[0], channel_id.value(), *is_host_transfer)); } case HloOpcode::kGetTupleElement: { optional<int64_t> index; attrs["index"] = {/*required=*/true, AttrTy::kInt64, &index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateGetTupleElement(*shape, operands[0], *index)); } case HloOpcode::kCall: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCall(*shape, operands, *to_apply)); } case HloOpcode::kReduceWindow: { optional<HloComputation*> reduce_computation; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduceWindow( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *window, *reduce_computation)); } case HloOpcode::kConvolution: { optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/true, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!feature_group_count) { feature_group_count = 1; } if (!batch_group_count) { batch_group_count = 1; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConvolve( *shape, /*lhs=*/operands[0], /*rhs=*/operands[1], feature_group_count.value(), batch_group_count.value(), *window, *dnums, precision_config)); } case HloOpcode::kFft: { optional<FftType> fft_type; optional<std::vector<int64_t>> fft_length; attrs["fft_type"] = {/*required=*/true, AttrTy::kFftType, &fft_type}; attrs["fft_length"] = {/*required=*/true, AttrTy::kBracedInt64List, &fft_length}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateFft( *shape, operands[0], *fft_type, *fft_length)); } case HloOpcode::kTriangularSolve: { TriangularSolveOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateTriangularSolve( *shape, operands[0], operands[1], options)); } case HloOpcode::kCompare: { optional<ComparisonDirection> direction; optional<Comparison::Type> type; attrs["direction"] = {/*required=*/true, AttrTy::kComparisonDirection, &direction}; attrs["type"] = {/*required=*/false, AttrTy::kComparisonType, &type}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateCompare( *shape, operands[0], operands[1], *direction, type)); } case HloOpcode::kCholesky: { CholeskyOptions options; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || (allow_attributes && !ParseAttributesAsProtoMessage( /*non_proto_attrs=*/attrs, &options))) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateCholesky(*shape, operands[0], options)); } case HloOpcode::kBroadcast: { if (!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) { return nullptr; } // The `dimensions` attr is optional if the broadcasted operand is a // scalar; in that case we can infer it to be {}. bool operand_is_scalar = ShapeUtil::IsScalar(operands[0]->shape()); optional<std::vector<int64_t>> broadcast_dimensions; attrs["dimensions"] = {/*required=*/!operand_is_scalar, AttrTy::kBracedInt64List, &broadcast_dimensions}; if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operand_is_scalar && !broadcast_dimensions.has_value()) { broadcast_dimensions.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBroadcast( *shape, operands[0], *broadcast_dimensions)); } case HloOpcode::kConcatenate: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes) || dimensions->size() != 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConcatenate( *shape, operands, dimensions->at(0))); } case HloOpcode::kMap: { optional<HloComputation*> to_apply; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &to_apply}; optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/false, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateMap(*shape, operands, *to_apply)); } case HloOpcode::kReduce: { optional<HloComputation*> reduce_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &reduce_computation}; optional<std::vector<int64_t>> dimensions_to_reduce; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions_to_reduce}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2) { TokenError(StrCat("expects an even number of operands, but has ", operands.size(), " operands")); return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReduce( *shape, /*operands=*/ absl::Span<HloInstruction* const>(operands).subspan( 0, operands.size() / 2), /*init_values=*/ absl::Span<HloInstruction* const>(operands).subspan(operands.size() / 2), *dimensions_to_reduce, *reduce_computation)); } case HloOpcode::kReverse: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateReverse(*shape, operands[0], *dimensions)); } case HloOpcode::kSelectAndScatter: { optional<HloComputation*> select; attrs["select"] = {/*required=*/true, AttrTy::kHloComputation, &select}; optional<HloComputation*> scatter; attrs["scatter"] = {/*required=*/true, AttrTy::kHloComputation, &scatter}; optional<Window> window; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!window) { window.emplace(); } if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSelectAndScatter( *shape, /*operand=*/operands[0], *select, *window, /*source=*/operands[1], /*init_value=*/operands[2], *scatter)); } case HloOpcode::kSlice: { optional<SliceRanges> slice_ranges; attrs["slice"] = {/*required=*/true, AttrTy::kSliceRanges, &slice_ranges}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSlice( *shape, operands[0], slice_ranges->starts, slice_ranges->limits, slice_ranges->strides)); } case HloOpcode::kDynamicSlice: { optional<std::vector<int64_t>> dynamic_slice_sizes; attrs["dynamic_slice_sizes"] = { /*required=*/true, AttrTy::kBracedInt64List, &dynamic_slice_sizes}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.empty()) { TokenError("Expected at least one operand."); return nullptr; } if (!(operands.size() == 2 && operands[1]->shape().rank() == 1) && operands.size() != 1 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicSlice( *shape, /*operand=*/operands[0], /*start_indices=*/absl::MakeSpan(operands).subspan(1), *dynamic_slice_sizes)); } case HloOpcode::kDynamicUpdateSlice: { if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() < 2) { TokenError("Expected at least two operands."); return nullptr; } if (!(operands.size() == 3 && operands[2]->shape().rank() == 1) && operands.size() != 2 + operands[0]->shape().rank()) { TokenError("Wrong number of operands."); return nullptr; } return builder->AddInstruction(HloInstruction::CreateDynamicUpdateSlice( *shape, /*operand=*/operands[0], /*update=*/operands[1], /*start_indices=*/absl::MakeSpan(operands).subspan(2))); } case HloOpcode::kTranspose: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateTranspose(*shape, operands[0], *dimensions)); } case HloOpcode::kBatchNormTraining: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/3)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormTraining( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], *epsilon, *feature_index)); } case HloOpcode::kBatchNormInference: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormInference( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*offset=*/operands[2], /*mean=*/operands[3], /*variance=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kBatchNormGrad: { optional<float> epsilon; attrs["epsilon"] = {/*required=*/true, AttrTy::kFloat, &epsilon}; optional<int64_t> feature_index; attrs["feature_index"] = {/*required=*/true, AttrTy::kInt64, &feature_index}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/5)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateBatchNormGrad( *shape, /*operand=*/operands[0], /*scale=*/operands[1], /*mean=*/operands[2], /*variance=*/operands[3], /*grad_output=*/operands[4], *epsilon, *feature_index)); } case HloOpcode::kPad: { optional<PaddingConfig> padding; attrs["padding"] = {/*required=*/true, AttrTy::kPaddingConfig, &padding}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreatePad( *shape, operands[0], /*padding_value=*/operands[1], *padding)); } case HloOpcode::kFusion: { optional<HloComputation*> fusion_computation; attrs["calls"] = {/*required=*/true, AttrTy::kHloComputation, &fusion_computation}; optional<HloInstruction::FusionKind> fusion_kind; attrs["kind"] = {/*required=*/true, AttrTy::kFusionKind, &fusion_kind}; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } auto instr = builder->AddInstruction(HloInstruction::CreateFusion( *shape, *fusion_kind, operands, *fusion_computation)); auto fusion_instr = Cast<HloFusionInstruction>(instr); if (output_to_operand_aliasing.has_value()) { fusion_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } return instr; } case HloOpcode::kInfeed: { optional<std::string> config; attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } // We need to know the infeed data shape to construct the infeed // instruction. This is the zero-th element of the tuple-shaped output of // the infeed instruction. ShapeUtil::GetTupleElementShape will check fail // if the shape is not a non-empty tuple, so add guard so an error message // can be emitted instead of a check fail if (!shape->IsTuple() && !ShapeUtil::IsEmptyTuple(*shape)) { TokenError("infeed must have a non-empty tuple shape"); return nullptr; } return builder->AddInstruction(HloInstruction::CreateInfeed( ShapeUtil::GetTupleElementShape(*shape, 0), operands[0], config ? *config : "")); } case HloOpcode::kOutfeed: { optional<std::string> config; optional<Shape> outfeed_shape; attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config}; attrs["outfeed_shape"] = {/*required=*/false, AttrTy::kShape, &outfeed_shape}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } HloInstruction* const outfeed_input = operands[0]; HloInstruction* const outfeed_token = operands[1]; const Shape shape = outfeed_shape.has_value() ? *outfeed_shape : outfeed_input->shape(); return builder->AddInstruction(HloInstruction::CreateOutfeed( shape, outfeed_input, outfeed_token, config ? *config : "")); } case HloOpcode::kRng: { optional<RandomDistribution> distribution; attrs["distribution"] = {/*required=*/true, AttrTy::kDistribution, &distribution}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRng(*shape, *distribution, operands)); } case HloOpcode::kRngGetAndUpdateState: { optional<int64_t> delta; attrs["delta"] = {/*required=*/true, AttrTy::kInt64, &delta}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/0)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction( HloInstruction::CreateRngGetAndUpdateState(*shape, *delta)); } case HloOpcode::kRngBitGenerator: { optional<RandomAlgorithm> algorithm; attrs["algorithm"] = {/*required=*/true, AttrTy::kRandomAlgorithm, &algorithm}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateRngBitGenerator( *shape, operands[0], *algorithm)); } case HloOpcode::kReducePrecision: { optional<int64_t> exponent_bits; optional<int64_t> mantissa_bits; attrs["exponent_bits"] = {/*required=*/true, AttrTy::kInt64, &exponent_bits}; attrs["mantissa_bits"] = {/*required=*/true, AttrTy::kInt64, &mantissa_bits}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateReducePrecision( *shape, operands[0], static_cast<int>(*exponent_bits), static_cast<int>(*mantissa_bits))); } case HloOpcode::kConditional: { optional<HloComputation*> true_computation; optional<HloComputation*> false_computation; optional<std::vector<HloComputation*>> branch_computations; if (!preset_operands && !ParseOperands(&operands, builder)) { return nullptr; } if (!ShapeUtil::IsScalar(operands[0]->shape())) { TokenError("The first operand must be a scalar"); return nullptr; } const bool branch_index_is_bool = operands[0]->shape().element_type() == PRED; if (branch_index_is_bool) { attrs["true_computation"] = {/*required=*/true, AttrTy::kHloComputation, &true_computation}; attrs["false_computation"] = { /*required=*/true, AttrTy::kHloComputation, &false_computation}; } else { if (operands[0]->shape().element_type() != S32) { TokenError("The first operand must be a scalar of PRED or S32"); return nullptr; } attrs["branch_computations"] = {/*required=*/true, AttrTy::kBracedHloComputationList, &branch_computations}; } if (!ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (branch_index_is_bool) { branch_computations.emplace({*true_computation, *false_computation}); } if (branch_computations->empty() || operands.size() != branch_computations->size() + 1) { return nullptr; } if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateConditional( *shape, /*branch_index=*/operands[0], absl::MakeSpan(*branch_computations), absl::MakeSpan(operands).subspan(1))); } case HloOpcode::kCustomCall: { optional<std::string> custom_call_target; optional<Window> window; optional<ConvolutionDimensionNumbers> dnums; optional<int64_t> feature_group_count; optional<int64_t> batch_group_count; optional<std::vector<Shape>> operand_layout_constraints; optional<bool> custom_call_has_side_effect; optional<HloComputation*> to_apply; optional< std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>> output_to_operand_aliasing; optional<PaddingType> padding_type; optional<std::vector<HloComputation*>> called_computations; optional<CustomCallSchedule> custom_call_schedule; optional<CustomCallApiVersion> api_version; attrs["custom_call_target"] = {/*required=*/true, AttrTy::kString, &custom_call_target}; attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window}; attrs["dim_labels"] = {/*required=*/false, AttrTy::kConvolutionDimensionNumbers, &dnums}; attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64, &feature_group_count}; attrs["batch_group_count"] = {/*required=*/false, AttrTy::kInt64, &batch_group_count}; attrs["operand_layout_constraints"] = { /*required=*/false, AttrTy::kShapeList, &operand_layout_constraints}; attrs["custom_call_has_side_effect"] = {/*required=*/false, AttrTy::kBool, &custom_call_has_side_effect}; attrs["to_apply"] = {/*required=*/false, AttrTy::kHloComputation, &to_apply}; attrs["called_computations"] = {/*required=*/false, AttrTy::kBracedHloComputationList, &called_computations}; attrs["output_to_operand_aliasing"] = {/*required=*/false, AttrTy::kInstructionAliasing, &output_to_operand_aliasing}; attrs["padding_type"] = {/*required=*/false, AttrTy::kPaddingType, &padding_type}; optional<Literal> literal; attrs["literal"] = {/*required=*/false, AttrTy::kLiteral, &literal}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; HloInstruction* instruction; if (called_computations.has_value() && to_apply.has_value()) { TokenError( "A single instruction can't have both to_apply and " "calls field"); return nullptr; } attrs["schedule"] = {/*required=*/false, AttrTy::kCustomCallSchedule, &custom_call_schedule}; attrs["api_version"] = {/*required=*/false, AttrTy::kCustomCallApiVersion, &api_version}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (api_version.has_value() && *api_version == CustomCallApiVersion::API_VERSION_UNSPECIFIED) { TokenError(StrCat("Invalid API version: ", CustomCallApiVersion_Name(*api_version))); return nullptr; } if (operand_layout_constraints.has_value()) { if (!LayoutUtil::HasLayout(*shape)) { TokenError("Layout must be set on layout-constrained custom call"); return nullptr; } if (operands.size() != operand_layout_constraints->size()) { TokenError(StrCat("Expected ", operands.size(), " operand layout constraints, ", operand_layout_constraints->size(), " given")); return nullptr; } for (int64_t i = 0; i < operands.size(); ++i) { const Shape& operand_shape_with_layout = (*operand_layout_constraints)[i]; if (!LayoutUtil::HasLayout(operand_shape_with_layout)) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " does not have a layout")); return nullptr; } if (!ShapeUtil::Compatible(operand_shape_with_layout, operands[i]->shape())) { TokenError(StrCat( "Operand layout constraint shape ", ShapeUtil::HumanStringWithLayout(operand_shape_with_layout), " for operand ", i, " is not compatible with operand shape ", ShapeUtil::HumanStringWithLayout(operands[i]->shape()))); return nullptr; } } instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, *operand_layout_constraints, "")); } else { if (to_apply.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *to_apply, *custom_call_target, "")); } else if (called_computations.has_value()) { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *called_computations, *custom_call_target, "")); } else { instruction = builder->AddInstruction(HloInstruction::CreateCustomCall( *shape, operands, *custom_call_target, "")); } } auto custom_call_instr = Cast<HloCustomCallInstruction>(instruction); if (window.has_value()) { custom_call_instr->set_window(*window); } if (dnums.has_value()) { custom_call_instr->set_convolution_dimension_numbers(*dnums); } if (feature_group_count.has_value()) { custom_call_instr->set_feature_group_count(*feature_group_count); } if (batch_group_count.has_value()) { custom_call_instr->set_batch_group_count(*batch_group_count); } if (padding_type.has_value()) { custom_call_instr->set_padding_type(*padding_type); } if (custom_call_has_side_effect.has_value()) { custom_call_instr->set_custom_call_has_side_effect( *custom_call_has_side_effect); } if (custom_call_schedule.has_value()) { custom_call_instr->set_custom_call_schedule(*custom_call_schedule); } if (api_version.has_value()) { custom_call_instr->set_api_version(*api_version); } if (output_to_operand_aliasing.has_value()) { custom_call_instr->set_output_to_operand_aliasing( std::move(*output_to_operand_aliasing)); } if (literal.has_value()) { custom_call_instr->set_literal(std::move(*literal)); } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( operands.size(), PrecisionConfig::DEFAULT); } *custom_call_instr->mutable_precision_config() = precision_config; return instruction; } case HloOpcode::kDot: { optional<std::vector<int64_t>> lhs_contracting_dims; attrs["lhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &lhs_contracting_dims}; optional<std::vector<int64_t>> rhs_contracting_dims; attrs["rhs_contracting_dims"] = { /*required=*/false, AttrTy::kBracedInt64List, &rhs_contracting_dims}; optional<std::vector<int64_t>> lhs_batch_dims; attrs["lhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &lhs_batch_dims}; optional<std::vector<int64_t>> rhs_batch_dims; attrs["rhs_batch_dims"] = {/*required=*/false, AttrTy::kBracedInt64List, &rhs_batch_dims}; optional<std::vector<PrecisionConfig::Precision>> operand_precision; attrs["operand_precision"] = {/*required=*/false, AttrTy::kPrecisionList, &operand_precision}; std::vector<SparsityDescriptor> sparsity; attrs["sparsity"] = {/*required=*/false, AttrTy::kSparsityDescriptor, &sparsity}; optional<PrecisionConfig::Algorithm> algorithm; attrs["algorithm"] = {/*required=*/false, AttrTy::kPrecisionAlgorithm, &algorithm}; LocTy loc = lexer_.GetLoc(); if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } int expected_size = HloDotInstruction::kOperands + sparsity.size(); if (sparsity.size() > HloDotInstruction::kOperands) { Error(loc, StrCat("too many sparse dot descriptors: ", sparsity.size())); return nullptr; } if (operands.size() != expected_size) { Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands.size(), " operands")); return nullptr; } DotDimensionNumbers dnum; if (lhs_contracting_dims) { *dnum.mutable_lhs_contracting_dimensions() = { lhs_contracting_dims->begin(), lhs_contracting_dims->end()}; } if (rhs_contracting_dims) { *dnum.mutable_rhs_contracting_dimensions() = { rhs_contracting_dims->begin(), rhs_contracting_dims->end()}; } if (lhs_batch_dims) { *dnum.mutable_lhs_batch_dimensions() = {lhs_batch_dims->begin(), lhs_batch_dims->end()}; } if (rhs_batch_dims) { *dnum.mutable_rhs_batch_dimensions() = {rhs_batch_dims->begin(), rhs_batch_dims->end()}; } PrecisionConfig precision_config; if (operand_precision) { *precision_config.mutable_operand_precision() = { operand_precision->begin(), operand_precision->end()}; } else { precision_config.mutable_operand_precision()->Resize( HloDotInstruction::kOperands, PrecisionConfig::DEFAULT); } if (algorithm) { precision_config.set_algorithm(*algorithm); } if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDot( *shape, operands[0], operands[1], dnum, precision_config, sparsity, absl::MakeSpan(operands).subspan(HloDotInstruction::kOperands))); } case HloOpcode::kGather: { optional<std::vector<int64_t>> offset_dims; attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &offset_dims}; optional<std::vector<int64_t>> collapsed_slice_dims; attrs["collapsed_slice_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims}; optional<std::vector<int64_t>> start_index_map; attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List, &start_index_map}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<std::vector<int64_t>> slice_sizes; attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List, &slice_sizes}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } GatherDimensionNumbers dim_numbers = HloGatherInstruction::MakeGatherDimNumbers( /*offset_dims=*/*offset_dims, /*collapsed_slice_dims=*/*collapsed_slice_dims, /*start_index_map=*/*start_index_map, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGather( *shape, /*operand=*/operands[0], /*start_indices=*/operands[1], dim_numbers, *slice_sizes, indices_are_sorted.value())); } case HloOpcode::kScatter: { optional<std::vector<int64_t>> update_window_dims; attrs["update_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &update_window_dims}; optional<std::vector<int64_t>> inserted_window_dims; attrs["inserted_window_dims"] = { /*required=*/true, AttrTy::kBracedInt64List, &inserted_window_dims}; optional<std::vector<int64_t>> scatter_dims_to_operand_dims; attrs["scatter_dims_to_operand_dims"] = {/*required=*/true, AttrTy::kBracedInt64List, &scatter_dims_to_operand_dims}; optional<int64_t> index_vector_dim; attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64, &index_vector_dim}; optional<HloComputation*> update_computation; attrs["to_apply"] = {/*required=*/true, AttrTy::kHloComputation, &update_computation}; optional<bool> indices_are_sorted = false; attrs["indices_are_sorted"] = {/*required=*/false, AttrTy::kBool, &indices_are_sorted}; optional<bool> unique_indices = false; attrs["unique_indices"] = {/*required=*/false, AttrTy::kBool, &unique_indices}; if ((!preset_operands && !ParseOperands(&operands, builder)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (operands.size() % 2 == 0) { TokenError(StrCat("expects an odd number of operands, but has ", operands.size(), " operands")); return nullptr; } ScatterDimensionNumbers dim_numbers = HloScatterInstruction::MakeScatterDimNumbers( /*update_window_dims=*/*update_window_dims, /*inserted_window_dims=*/*inserted_window_dims, /*scatter_dims_to_operand_dims=*/*scatter_dims_to_operand_dims, /*index_vector_dim=*/*index_vector_dim); if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { return nullptr; } auto input_count = operands.size() / 2; auto operand_span = absl::MakeConstSpan(operands); return builder->AddInstruction(HloInstruction::CreateScatter( *shape, operand_span.first(input_count), operands[input_count], operand_span.last(input_count), *update_computation, dim_numbers, indices_are_sorted.value(), unique_indices.value())); } case HloOpcode::kDomain: { DomainData domain; attrs["domain"] = {/*required=*/true, AttrTy::kDomain, &domain}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateDomain( *shape, operands[0], std::move(domain.exit_metadata), std::move(domain.entry_metadata))); } case HloOpcode::kGetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/1)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateGetDimensionSize( *shape, operands[0], (*dimensions)[0])); } case HloOpcode::kSetDimensionSize: { optional<std::vector<int64_t>> dimensions; attrs["dimensions"] = {/*required=*/true, AttrTy::kBracedInt64List, &dimensions}; if ((!preset_operands && !ParseOperands(&operands, builder, /*expected_size=*/2)) || !ParseAttributes(attrs, allow_attributes)) { return nullptr; } if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { return nullptr; } return builder->AddInstruction(HloInstruction::CreateSetDimensionSize( *shape, operands[0], operands[1], (*dimensions)[0])); } default: return nullptr; } } // NOLINT(readability/fn_size) [&](absl::FunctionRef<absl::StatusOr<Shape>()> infer) { if (shape.has_value()) { return true; } auto inferred = infer(); if (!inferred.ok()) { return TokenError( StrFormat("failed to infer shape for opcode: %s, error: %s", HloOpcodeString(opcode), inferred.status().message())); } shape = std::move(inferred).value(); return true; }; if (!maybe_infer_shape([&] { return ShapeInference::InferTopKShape(operands[0]->shape(), *k); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTernaryOpShape( opcode, operands[0], operands[1], operands[2]); })) { auto is_async_shape_correct = [](const Shape& shape) { return shape.IsTuple() && shape.tuple_shapes_size() >= 2 && shape.tuple_shapes(0).IsTuple(); }; if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferVariadicOpShape(opcode, arg_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferWhileShape( condition.value()->ComputeProgramShape(), body.value()->ComputeProgramShape(), operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeUtil::GetTupleElementShape(operands[0]->shape(), *index); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferCallShape( arg_shapes, to_apply.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReduceWindowShape( operands[0]->shape(), operands[1]->shape(), *window, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferConvolveShape( operands[0]->shape(), operands[1]->shape(), *feature_group_count, *batch_group_count, *window, *dnums, /*preferred_element_type=*/std::nullopt); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferFftShape(operands[0]->shape(), *fft_type, *fft_length); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTriangularSolveShape( operands[0]->shape(), operands[1]->shape(), options); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBinaryOpShape(opcode, operands[0], operands[1]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferCholeskyShape(operands[0]->shape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBroadcastShape(operands[0]->shape(), *broadcast_dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferConcatOpShape(arg_shapes, dimensions->at(0)); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferMapShape( arg_shapes, to_apply.value()->ComputeProgramShape(), *dimensions); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 2> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferReduceShape( arg_shapes, *dimensions_to_reduce, reduce_computation.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferReverseShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSelectAndScatterShape( operands[0]->shape(), select.value()->ComputeProgramShape(), *window, operands[1]->shape(), operands[2]->shape(), scatter.value()->ComputeProgramShape()); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferTransposeShape(operands[0]->shape(), *dimensions); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormTrainingShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormInferenceShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferBatchNormGradShape( operands[0]->shape(), operands[1]->shape(), operands[2]->shape(), operands[3]->shape(), operands[4]->shape(), *feature_index); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferPadShape( operands[0]->shape(), operands[1]->shape(), *padding); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<ProgramShape, 2> branch_computation_shapes; branch_computation_shapes.reserve(branch_computations->size()); for (auto* computation : *branch_computations) { branch_computation_shapes.push_back( computation->ComputeProgramShape()); } absl::InlinedVector<Shape, 2> branch_operand_shapes; branch_operand_shapes.reserve(operands.size() - 1); for (int i = 1; i < operands.size(); ++i) { branch_operand_shapes.push_back(operands[i]->shape()); } return ShapeInference::InferConditionalShape( operands[0]->shape(), branch_computation_shapes, branch_operand_shapes); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferDotOpShape( operands[0]->shape(), operands[1]->shape(), dnum, /*preferred_element_type=*/std::nullopt, sparsity); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGatherShape(operands[0]->shape(), operands[1]->shape(), dim_numbers, *slice_sizes); })) { if (!maybe_infer_shape([&] { absl::InlinedVector<const Shape*, 3> arg_shapes; arg_shapes.reserve(operands.size()); for (auto* operand : operands) { arg_shapes.push_back(&operand->shape()); } return ShapeInference::InferScatterShape( arg_shapes, update_computation.value()->ComputeProgramShape(), dim_numbers); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferUnaryOpShape(opcode, operands[0]); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferGetDimensionSizeShape( operands[0]->shape(), dimensions->at(0)); })) { if (!maybe_infer_shape([&] { return ShapeInference::InferSetDimensionSizeShape( operands[0]->shape(), operands[1]->shape(), dimensions->at(0)); })) { bool HloParserImpl::ParseSharding(OpSharding* sharding) { // A single sharding starts with '{' and is not followed by '{'. // A tuple sharding starts with '{' and is followed by '{', or is '{''}' for // an empty tuple. if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kRbrace) { return ParseSingleSharding(sharding, /*lbrace_pre_lexed=*/true); } // Tuple sharding. // Allow empty tuple shardings. if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseSingleSharding(sharding->add_tuple_shardings(), /*lbrace_pre_lexed=*/false)) { return false; } } while (EatIfPresent(TokKind::kComma)); } sharding->set_type(OpSharding::TUPLE); return ParseToken(TokKind::kRbrace, "expected '}' to end sharding attribute"); } bool HloParserImpl::ParseFrontendAttributes( FrontendAttributes* frontend_attributes) { CHECK(frontend_attributes != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start frontend attributes")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { std::string attribute; if (!ParseAttributeName(&attribute)) { return false; } if (lexer_.GetKind() != TokKind::kString) { return false; } (*frontend_attributes->mutable_map())[attribute] = lexer_.GetStrVal(); lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expects '}' at the end of frontend attributes"); } bool HloParserImpl::ParseStatisticsViz(StatisticsViz* statistics_viz) { CHECK(statistics_viz != nullptr); if (!ParseToken(TokKind::kLbrace, "expected '{' to start statistics")) { return false; } if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { // index must exist std::string visualizing_index_attr_name; if (!ParseAttributeName(&visualizing_index_attr_name)) { return false; } if (lexer_.GetKind() != TokKind::kInt) { return false; } statistics_viz->set_stat_index_to_visualize(lexer_.GetInt64Val()); lexer_.Lex(); // then process statistics while (EatIfPresent(TokKind::kComma)) { std::string stat_name; if (!ParseAttributeName(&stat_name)) { return false; } if (lexer_.GetKind() != TokKind::kDecimal && lexer_.GetKind() != TokKind::kInt) { return false; } Statistic statistic; statistic.set_stat_name(stat_name); statistic.set_stat_val(lexer_.GetKind() == TokKind::kDecimal ? lexer_.GetDecimalVal() : lexer_.GetInt64Val()); lexer_.Lex(); *statistics_viz->add_statistics() = std::move(statistic); } } return ParseToken(TokKind::kRbrace, "expects '}' at the end of statistics"); } bool HloParserImpl::ParseSingleSharding(OpSharding* sharding, bool lbrace_pre_lexed) { if (!lbrace_pre_lexed && !ParseToken(TokKind::kLbrace, "expected '{' to start sharding attribute")) { return false; } LocTy loc = lexer_.GetLoc(); bool maximal = false; bool replicated = false; bool manual = false; bool unknown = false; bool last_tile_dim_replicate = false; bool last_tile_dims = false; bool shard_like = false; bool shard_as = false; int64_t shard_group_id; std::vector<int64_t> devices; std::vector<int64_t> tile_assignment_dimensions; std::vector<int64_t> iota_reshape_dims; std::vector<int> iota_transpose_perm; std::vector<OpSharding::Type> subgroup_types; while (lexer_.GetKind() != TokKind::kRbrace) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: maximal = true; lexer_.Lex(); break; case TokKind::kw_replicated: replicated = true; lexer_.Lex(); break; case TokKind::kw_manual: manual = true; lexer_.Lex(); break; case TokKind::kw_unknown: unknown = true; lexer_.Lex(); break; case TokKind::kAttributeName: { if (lexer_.GetStrVal() == "device") { if (lexer_.Lex() != TokKind::kInt) { return TokenError("device= attribute must be an integer"); } devices = {lexer_.GetInt64Val()}; lexer_.Lex(); } else if (lexer_.GetStrVal() == "devices") { lexer_.Lex(); if (!ParseToken(TokKind::kLsquare, "expected '[' to start sharding devices shape")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } tile_assignment_dimensions.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding devices shape")) { return false; } if (lexer_.GetKind() == TokKind::kLeq) { lexer_.Lex(); if (!ParseToken( TokKind::kLsquare, "expected '[' to start sharding iota_reshape_dims")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } iota_reshape_dims.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (iota_reshape_dims.empty()) { return TokenError("expected non-empty iota_reshape_dims"); } if (!ParseToken(TokKind::kRsquare, "expected ']' to end sharding iota_reshape_dims")) { return false; } if (iota_reshape_dims.size() == 1) { iota_transpose_perm.push_back(0); } else { if (lexer_.GetKind() != TokKind::kIdent || lexer_.GetStrVal() != "T") { return TokenError( "expected 'T(' to start sharding devices " "iota_transpose_perm"); } lexer_.Lex(); if (!ParseToken(TokKind::kLparen, "expected 'T(' to start sharding devices " "iota_transpose_perm")) { return false; } do { int64_t dim; if (!ParseInt64(&dim)) { return false; } if (dim >= iota_reshape_dims.size()) { return TokenError(absl::StrFormat( "Out of range iota minor_to_major value %lld.", dim)); } iota_transpose_perm.push_back(dim); } while (EatIfPresent(TokKind::kComma)); if (!ParseToken(TokKind::kRparen, "expected ')' to end sharding devices " "iota_transpose_perm")) { return false; } } } else { do { int64_t device; if (!ParseInt64(&device)) { return false; } devices.push_back(device); } while (EatIfPresent(TokKind::kComma)); } } else if (lexer_.GetStrVal() == "metadata") { lexer_.Lex(); if (!ParseSingleOrListMetadata(sharding->mutable_metadata())) { return false; } } else if (lexer_.GetStrVal() == "last_tile_dims") { last_tile_dims = true; lexer_.Lex(); if (!ParseListShardingType(&subgroup_types)) { return false; } } else { return TokenError( "unknown attribute in sharding: expected device=, devices= " "metadata= or last_tile_dims= "); } break; } case TokKind::kw_last_tile_dim_replicate: last_tile_dim_replicate = true; lexer_.Lex(); break; case TokKind::kw_shard_as: { shard_as = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kw_shard_like: { shard_like = true; lexer_.Lex(); if (!ParseInt64(&shard_group_id)) { return false; } break; } case TokKind::kRbrace: break; default: return TokenError("unexpected token"); } } if (replicated) { if (!devices.empty()) { return Error(loc, "replicated shardings should not have any devices assigned"); } sharding->set_type(OpSharding::REPLICATED); } else if (maximal) { if (devices.size() != 1) { return Error(loc, "maximal shardings should have exactly one device assigned"); } sharding->set_type(OpSharding::MAXIMAL); sharding->add_tile_assignment_devices(devices[0]); } else if (manual) { if (!devices.empty()) { return Error(loc, "manual shardings should not have any devices assigned"); } sharding->set_type(OpSharding::MANUAL); } else if (unknown) { if (!devices.empty()) { return Error(loc, "unknown shardings should not have any devices assigned"); } sharding->set_type(OpSharding::UNKNOWN); } else { if (tile_assignment_dimensions.empty()) { return Error( loc, "non-maximal shardings must have a tile assignment list including " "dimensions"); } sharding->set_type(OpSharding::OTHER); for (int64_t dim : tile_assignment_dimensions) { sharding->add_tile_assignment_dimensions(dim); } if (iota_transpose_perm.size() != iota_reshape_dims.size()) { return Error(loc, absl::StrFormat( "iota_transpose_perm should have the same rank as " "iota_reshape_dims : expected %lld, saw %lld.", iota_reshape_dims.size(), iota_transpose_perm.size())); } if (!iota_reshape_dims.empty()) { CHECK(devices.empty()); absl::c_copy(iota_reshape_dims, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_reshape_dims())); absl::c_copy(iota_transpose_perm, tsl::protobuf::RepeatedFieldBackInserter( sharding->mutable_iota_transpose_perm())); } else { if (devices.size() <= 1) { return Error( loc, "non-maximal shardings must have more than one device assigned"); } for (int64_t device : devices) { sharding->add_tile_assignment_devices(device); } } if (last_tile_dims) { for (OpSharding::Type type : subgroup_types) { sharding->add_last_tile_dims(type); } } else { sharding->set_replicate_on_last_tile_dim(last_tile_dim_replicate); } } if (shard_as || shard_like) { sharding->set_is_shard_group(true); sharding->set_shard_group_id(shard_group_id); if (shard_as) { sharding->set_shard_group_type(OpSharding::AS); } else { sharding->set_shard_group_type(OpSharding::LIKE); } } else { sharding->set_is_shard_group(false); } lexer_.Lex(); return true; } bool HloParserImpl::ParseParameterReplication( ParameterReplication* parameter_replication) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start parameter_replication attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (lexer_.GetKind() == TokKind::kw_true) { parameter_replication->add_replicated_at_leaf_buffers(true); } else if (lexer_.GetKind() == TokKind::kw_false) { parameter_replication->add_replicated_at_leaf_buffers(false); } else { return false; } lexer_.Lex(); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end parameter_replication attribute"); } bool HloParserImpl::ParseBooleanListOrSingleBoolean(BoolList* boolean_list) { if (lexer_.GetKind() != TokKind::kLbrace && lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { TokenError("Expected list of booleans or true/false value"); return false; } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; if (parse_boolean()) { return true; } if (!ParseToken(TokKind::kLbrace, "expected '{' to start boolean list attribute")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!parse_boolean()) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end boolean list attribute"); } auto parse_boolean = [this, boolean_list]() { if (lexer_.GetKind() == TokKind::kw_true) { boolean_list->push_back(true); lexer_.Lex(); return true; } else if (lexer_.GetKind() == TokKind::kw_false) { boolean_list->push_back(false); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParseReplicaGroupsOnly( std::vector<ReplicaGroup>* replica_groups) { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } *replica_groups = CreateReplicaGroups(result); return true; } bool HloParserImpl::ParseDomain(DomainData* domain) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> kind; optional<OpSharding> entry_sharding; optional<OpSharding> exit_sharding; attrs["kind"] = {/*required=*/true, AttrTy::kString, &kind}; attrs["entry"] = {/*required=*/true, AttrTy::kSharding, &entry_sharding}; attrs["exit"] = {/*required=*/true, AttrTy::kSharding, &exit_sharding}; if (!ParseSubAttributes(attrs)) { return false; } if (*kind == ShardingMetadata::KindName()) { auto entry_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*entry_sharding).value()); auto exit_sharding_ptr = std::make_unique<HloSharding>( HloSharding::FromProto(*exit_sharding).value()); domain->entry_metadata = std::make_unique<ShardingMetadata>(std::move(entry_sharding_ptr)); domain->exit_metadata = std::make_unique<ShardingMetadata>(std::move(exit_sharding_ptr)); } else { return TokenError(StrCat("unsupported domain kind: ", *kind)); } return true; } bool HloParserImpl::ParseInstructionNames( std::vector<HloInstruction*>* instructions) { if (!ParseToken(TokKind::kLbrace, "expects '{' at the beginning of instruction name list")) { return false; } LocTy loc = lexer_.GetLoc(); do { std::string name; if (!ParseName(&name)) { return Error(loc, "expects a instruction name"); } std::pair<HloInstruction*, LocTy>* instr = FindInstruction(name); if (!instr) { return TokenError(StrFormat("instruction '%s' is not defined", name)); } instructions->push_back(instr->first); } while (EatIfPresent(TokKind::kComma)); return ParseToken(TokKind::kRbrace, "expects '}' at the end of instruction name list"); } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } std::string StringifyValue(T val) { if constexpr (is_complex_v<T>) { return StrFormat("(%f, %f)", val.real(), val.imag()); } else { return StrCat(val); } } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, ParsedElemT value) { if constexpr (std::is_floating_point_v<ParsedElemT>) { auto value_as_native_t = static_cast<LiteralNativeT>(value); auto value_double_converted = static_cast<ParsedElemT>(value_as_native_t); if (!IsFinite(value) || IsFinite(value_double_converted)) { value = value_double_converted; } } PrimitiveType literal_ty = primitive_util::NativeToPrimitiveType<LiteralNativeT>(); if (!IsFinite(value)) { // Skip range checking for non-finite value. } else if constexpr (std::is_unsigned<LiteralNativeT>::value) { static_assert(std::is_same_v<ParsedElemT, int64_t> || std::is_same_v<ParsedElemT, bool>, "Unimplemented checking for ParsedElemT"); const uint64_t unsigned_value = value; const uint64_t upper_bound = static_cast<uint64_t>(std::numeric_limits<LiteralNativeT>::max()); if (unsigned_value > upper_bound) { // Value is out of range for LiteralNativeT. return Error(loc, StrCat("value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [0, ", upper_bound, "].")); } } else if (value > static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::max()) || value < static_cast<ParsedElemT>( MinMaxFiniteValue<LiteralNativeT>::min())) { // Value is out of range for LiteralNativeT. return Error( loc, StrCat( "value ", value, " is out of range for literal's primitive type ", PrimitiveType_Name(literal_ty), " namely [", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::min()), ", ", static_cast<ParsedElemT>(MinMaxFiniteValue<LiteralNativeT>::max()), "].")); } return true; } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } bool HloParserImpl::CheckParsedValueIsInRange(LocTy loc, std::complex<double> value) { // e.g. `float` for std::complex<float> using LiteralComplexComponentT = decltype(std::real(std::declval<LiteralNativeT>())); // We could do simply // // return CheckParsedValueIsInRange<LiteralNativeT>(std::real(value)) && // CheckParsedValueIsInRange<LiteralNativeT>(std::imag(value)); // // but this would give bad error messages on failure. auto check_component = [&](absl::string_view name, double v) { if (!std::isfinite(v)) { // Skip range-checking for non-finite values. return true; } double min = MinMaxFiniteValue<LiteralComplexComponentT>::min(); double max = MinMaxFiniteValue<LiteralComplexComponentT>::max(); if (v < min || v > max) { // Value is out of range for LitearlComplexComponentT. return Error( loc, StrCat(name, " part ", v, " is out of range for literal's primitive type ", PrimitiveType_Name( primitive_util::NativeToPrimitiveType<LiteralNativeT>()), ", namely [", min, ", ", max, "].")); } return true; }; return check_component("real", std::real(value)) && check_component("imaginary", std::imag(value)); } auto check_component = [&](absl::string_view name, double v) { auto check_component = [&](absl::string_view name, double v) { bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } bool HloParserImpl::SetValueInLiteralHelper(LocTy loc, ParsedElemT value, int64_t index, Literal* literal) { if (!CheckParsedValueIsInRange<LiteralNativeT>(loc, value)) { return false; } // Check that the index is in range and assign into the literal if (index >= ShapeUtil::ElementsIn(literal->shape())) { return Error(loc, StrCat("tries to set value ", StringifyValue(value), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the index is out of range")); } using ParsedElemComponentT = typename ComponentType<ParsedElemT>::Type; using LiteralNativeComponentT = typename ComponentType<LiteralNativeT>::Type; const auto handle_nan = [this, literal, index, loc]( ParsedElemComponentT parsed_value_component, LiteralNativeComponentT* literal_value_component) { if (!std::isnan(static_cast<double>(parsed_value_component))) { return true; } auto nan_payload = GetNanPayload(parsed_value_component); if constexpr (NanPayloadBits<LiteralNativeComponentT>() > 0) { if (nan_payload == QuietNanWithoutPayload<double>()) { nan_payload = QuietNanWithoutPayload<LiteralNativeComponentT>(); } const auto kLargestPayload = NanPayloadBitMask<LiteralNativeComponentT>(); if (nan_payload > kLargestPayload) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but the NaN payload is out of range (0x", absl::Hex(kLargestPayload), ")")); } *literal_value_component = NanWithSignAndPayload<LiteralNativeComponentT>( /*sign=*/std::signbit( static_cast<double>(parsed_value_component)), /*nan_payload=*/nan_payload); } else { if (nan_payload != QuietNanWithoutPayload<double>()) { return Error( loc, StrCat("tries to set NaN payload 0x", absl::Hex(nan_payload), " to a literal in shape ", ShapeUtil::HumanString(literal->shape()), " at linear index ", index, ", but ", primitive_util::LowercasePrimitiveTypeName( literal->shape().element_type()), " does not support payloads")); } } return true; }; const ParsedElemComponentT parsed_real_value = GetReal(value); auto literal_real_value = static_cast<LiteralNativeComponentT>(parsed_real_value); if (std::is_floating_point_v<ParsedElemT> || std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_real_value)) { return false; } } const ParsedElemComponentT parsed_imag_value = GetImag(value); auto literal_imag_value = static_cast<LiteralNativeComponentT>(parsed_imag_value); if constexpr (std::is_same_v<ParsedElemT, std::complex<double>>) { if (!handle_nan(parsed_real_value, &literal_imag_value)) { return false; } } literal->data<LiteralNativeT>().at(index) = LiteralNativeFromRealImag<LiteralNativeT>(literal_real_value, literal_imag_value); return true; } [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( [this, literal, index, loc]( bool HloParserImpl::SetValueInLiteral(LocTy loc, int64_t value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_type_constant == PRED) { return SetValueInLiteralHelper<bool>(loc, static_cast<bool>(value), index, literal); } if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown integral primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, double value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << "unknown floating point primitive type " << PrimitiveType_Name(shape.element_type()); }, bool HloParserImpl::SetValueInLiteral(LocTy loc, bool value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); switch (shape.element_type()) { case PRED: return SetValueInLiteralHelper<bool>(loc, value, index, literal); default: LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not PRED type"; } } bool HloParserImpl::SetValueInLiteral(LocTy loc, std::complex<double> value, int64_t index, Literal* literal) { const Shape& shape = literal->shape(); return primitive_util::PrimitiveTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, shape.element_type()); } [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, [&](auto primitive_type_constant) -> bool { if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; return SetValueInLiteralHelper<NativeT>(loc, value, index, literal); } LOG(FATAL) << PrimitiveType_Name(shape.element_type()) << " is not a complex type"; }, bool HloParserImpl::ParseLiteral(Literal* literal) { if (lexer_.GetKind() == TokKind::kLparen) { // Consume Lparen lexer_.Lex(); std::vector<Literal> elements; while (lexer_.GetKind() != TokKind::kRparen) { Literal element; if (!ParseLiteral(&element)) { return TokenError("Fails when parsing tuple element"); } elements.emplace_back(std::move(element)); if (lexer_.GetKind() != TokKind::kRparen) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); // Consume Rparen return ParseToken(TokKind::kRparen, "expects ')' to close a tuple literal"); } Shape literal_shape; if (!ParseShape(&literal_shape)) { return false; } return ParseLiteral(literal, literal_shape); } bool HloParserImpl::ParseLiteral(Literal* literal, const Shape& shape) { return shape.IsTuple() ? ParseTupleLiteral(literal, shape) : ParseNonTupleLiteral(literal, shape); } bool HloParserImpl::ParseTupleLiteral(Literal* literal, const Shape& shape) { if (!ParseToken(TokKind::kLparen, "expects '(' in front of tuple elements")) { return false; } std::vector<Literal> elements(ShapeUtil::TupleElementCount(shape)); if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { // literal, (',' literal)* for (int i = 0; i < elements.size(); i++) { if (i > 0) { ParseToken(TokKind::kComma, "expects ',' to separate tuple elements"); } if (!ParseLiteral(&elements[i], ShapeUtil::GetTupleElementShape(shape, i))) { return TokenError(StrCat("expects the ", i, "th element")); } } } *literal = LiteralUtil::MakeTupleOwned(std::move(elements)); return ParseToken(TokKind::kRparen, StrCat("expects ')' at the end of the tuple with ", ShapeUtil::TupleElementCount(shape), "elements")); } bool HloParserImpl::ParseNonTupleLiteral(Literal* literal, const Shape& shape) { CHECK(LayoutUtil::IsDenseArray(shape)) << shape.ToString(true); return ParseDenseLiteral(literal, shape); } bool HloParserImpl::ParseDenseLiteral(Literal* literal, const Shape& shape) { // Cast `rank` to int because we call shape.dimensions(int rank) below, and if // `rank` is an int64_t, that's an implicit narrowing conversion, which is // implementation-defined behavior. const int rank = static_cast<int>(shape.rank()); // Create a literal with the given shape in default layout. *literal = LiteralUtil::CreateFromDimensions(shape.element_type(), shape.dimensions()); int64_t nest_level = 0; int64_t linear_index = 0; // elems_seen_per_dim[i] is how many elements or sub-arrays we have seen for // the dimension i. For example, to parse f32[2,3] {{1, 2, 3}, {4, 5, 6}}, // when we are parsing the 2nd '{' (right before '1'), we are seeing a // sub-array of the dimension 0, so elems_seen_per_dim[0]++. When we are at // the first '}' (right after '3'), it means the sub-array ends, and the // sub-array is supposed to contain exactly 3 elements, so check if // elems_seen_per_dim[1] is 3. std::vector<int64_t> elems_seen_per_dim(rank); auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; do { switch (lexer_.GetKind()) { default: return TokenError("unexpected token type in a literal"); case TokKind::kLbrace: { nest_level++; if (nest_level > rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees larger", rank)); } if (nest_level > 1) { elems_seen_per_dim[nest_level - 2]++; if (elems_seen_per_dim[nest_level - 2] > shape.dimensions(nest_level - 2)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees more", shape.dimensions(nest_level - 2), get_index_str(nest_level - 2))); } } lexer_.Lex(); break; } case TokKind::kRbrace: { if (nest_level == 0) { return TokenError("unexpected '}' token"); } nest_level--; if (elems_seen_per_dim[nest_level] != shape.dimensions(nest_level)) { return TokenError(absl::StrFormat( "expects %d elements in the %sth element, but sees %d", shape.dimensions(nest_level), get_index_str(nest_level), elems_seen_per_dim[nest_level])); } elems_seen_per_dim[nest_level] = 0; lexer_.Lex(); break; } case TokKind::kLparen: { if (!primitive_util::IsComplexType(shape.element_type())) { return TokenError( absl::StrFormat("unexpected '(' in literal. Parens are only " "valid for complex literals")); } std::complex<double> value; LocTy loc = lexer_.GetLoc(); if (!add_one_elem_seen() || !ParseComplex(&value) || !SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } break; } case TokKind::kDots: { if (nest_level != 1) { return TokenError(absl::StrFormat( "expects `...` at nest level 1, but sees it at nest level %d", nest_level)); } elems_seen_per_dim[0] = shape.dimensions(0); lexer_.Lex(); // Fill data with deterministic (garbage) values. Use static to avoid // creating identical constants which could potentially got CSE'ed // away. This is a best-effort approach to make sure replaying a HLO // gives us same optimized HLO graph. static uint32_t data = 0; // According to the System V ABI not all 8 bit values are valid booleans // - only the values 0 and 1 are allowed. So to avoid undefined // behaviour we mask elements of type PRED accordingly. The mask assumes // that the C++ data type `bool` is represented as a single byte. static_assert(sizeof(bool) == 1); constexpr uint32_t kBooleanMask = 0x01010101; constexpr uint32_t kNoMask = 0xFFFFFFFF; const uint32_t mask = (shape.element_type() == PRED) ? kBooleanMask : kNoMask; uint32_t* raw_data = static_cast<uint32_t*>(literal->untyped_data()); for (int64_t i = 0; i < literal->size_bytes() / 4; ++i) { raw_data[i] = data++ & mask; } uint8_t* raw_data_int8 = static_cast<uint8_t*>(literal->untyped_data()); static uint8_t data_int8 = 0; for (int64_t i = 0; i < literal->size_bytes() % 4; ++i) { raw_data_int8[literal->size_bytes() / 4 + i] = data_int8++ & mask; } break; } case TokKind::kComma: // Skip. lexer_.Lex(); break; case TokKind::kw_true: case TokKind::kw_false: case TokKind::kInt: case TokKind::kDecimal: case TokKind::kw_inf: case TokKind::kNegInf: { add_one_elem_seen(); if (lexer_.GetKind() == TokKind::kw_true || lexer_.GetKind() == TokKind::kw_false) { if (!SetValueInLiteral(lexer_.GetLoc(), lexer_.GetKind() == TokKind::kw_true, linear_index++, literal)) { return false; } lexer_.Lex(); } else if (primitive_util::IsIntegralType(shape.element_type()) || shape.element_type() == PRED) { LocTy loc = lexer_.GetLoc(); int64_t value; if (!ParseInt64(&value)) { return Error(loc, StrCat("expects integer for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else if (primitive_util::IsFloatingPointType(shape.element_type())) { LocTy loc = lexer_.GetLoc(); double value; if (!ParseDouble(&value)) { return Error( loc, StrCat("expect floating point value for primitive type: ", PrimitiveType_Name(shape.element_type()))); } if (!SetValueInLiteral(loc, value, linear_index++, literal)) { return false; } } else { return TokenError(StrCat("unsupported primitive type ", PrimitiveType_Name(shape.element_type()))); } break; } } // end of switch } while (nest_level > 0); *literal = literal->Relayout(shape.layout()); return true; } auto get_index_str = [&elems_seen_per_dim](int dim) -> std::string { std::vector<int64_t> elems_seen_until_dim(elems_seen_per_dim.begin(), elems_seen_per_dim.begin() + dim); return StrCat("[", StrJoin(elems_seen_until_dim, ",", [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), "]"); }; [](std::string* out, const int64_t num_elems) { StrAppend(out, num_elems - 1); }), auto add_one_elem_seen = [&] { if (rank > 0) { if (nest_level != rank) { return TokenError(absl::StrFormat( "expects nested array in rank %d, but sees %d", rank, nest_level)); } elems_seen_per_dim[rank - 1]++; if (elems_seen_per_dim[rank - 1] > shape.dimensions(rank - 1)) { return TokenError(absl::StrFormat( "expects %d elements on the minor-most dimension, but " "sees more", shape.dimensions(rank - 1))); } } return true; }; bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder) { CHECK(operands != nullptr); if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of operands")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { // Try to parse the operand as a name with an optional shape. If that // doesn't work, try again parsing it as a nested instruction. // // (Trying nested instructions second is important here: If you have a // giant HLO dump, it likely doesn't have any nested instructions, but // likely has tons of non-nested operands. Generating an error is slow -- // O(n) as of writing -- so we only want to hit the error branch in the // uncommon case.) HloLexer lexer_copy = lexer_; std::vector<std::string> saved_errors; std::swap(saved_errors, error_); bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); if (is_normal_operand) { error_ = std::move(saved_errors); continue; } // If parsing as a normal operand failed, try parsing as a nested // instruction. std::vector<std::string> normal_operand_errors; std::swap(error_, normal_operand_errors); lexer_ = lexer_copy; // Nested instructions can't have attributes because it's ambiguous // whether the comma separates an instruction from its attribute, or // whether the comma separates two instructions. LocTy loc = lexer_.GetLoc(); bool is_nested_instruction = ParseInstructionRhs( builder, /*name=*/"", loc, /*allow_attributes=*/false); if (is_nested_instruction) { operands->push_back(builder->last_added_instruction()); error_ = std::move(saved_errors); continue; } // If neither parsing as a normal operand nor parsing as a nested // instruction worked, fail. Return both sets of errors. std::vector<std::string> nested_instruction_errors; std::swap(error_, nested_instruction_errors); error_ = std::move(saved_errors); Error(loc, "cannot parse as an instruction name or as a nested instruction:"); error_.insert(error_.end(), std::make_move_iterator(normal_operand_errors.begin()), std::make_move_iterator(normal_operand_errors.end())); error_.insert(error_.end(), std::make_move_iterator(nested_instruction_errors.begin()), std::make_move_iterator(nested_instruction_errors.end())); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of operands"); } bool is_normal_operand = [&] { LocTy loc = lexer_.GetLoc(); std::string name; optional<Shape> shape; if (CanBeShape()) { shape.emplace(); if (!ParseShape(&shape.value())) { return false; } } if (!ParseName(&name)) { // When parsing a single instruction (as opposed to a whole module), // an HLO may have one or more operands with a shape but no name: // // foo = add(f32[10], f32[10]) // // create_missing_instruction_ is always non-null when parsing a // single instruction, and is responsible for creating kParameter // instructions for these operands. if (shape.has_value() && create_missing_instruction_ != nullptr && scoped_name_tables_.size() == 1) { name = ""; } else { return false; } } std::pair<HloInstruction*, LocTy>* instruction = FindInstruction(name, shape); if (instruction == nullptr) { return Error(loc, StrCat("instruction does not exist: ", name)); } // If this is a regular named operand, it must be followed by a comma or // a close-paren. If not, it has to be a named instruction. Don't // output an error here -- if it fails to parse as a named instruction // too, we'll just use that set of errors. auto next = lexer_.GetKind(); if (next != TokKind::kComma && next != TokKind::kRparen) { return false; } operands->push_back(instruction->first); return true; }(); bool HloParserImpl::ParseOperands(std::vector<HloInstruction*>* operands, HloComputation::Builder* builder, const int expected_size) { CHECK(operands != nullptr); LocTy loc = lexer_.GetLoc(); if (!ParseOperands(operands, builder)) { return false; } if (expected_size != operands->size()) { return Error(loc, StrCat("expects ", expected_size, " operands, but has ", operands->size(), " operands")); } return true; } bool HloParserImpl::ParseSubAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs) { LocTy loc = lexer_.GetLoc(); if (!ParseToken(TokKind::kLbrace, "expects '{' to start sub attributes")) { return false; } absl::flat_hash_set<std::string> seen_attrs; if (lexer_.GetKind() == TokKind::kRbrace) { // empty } else { do { EatIfPresent(TokKind::kComma); if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } while (lexer_.GetKind() != TokKind::kRbrace); } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("sub-attribute %s is expected but not seen", attr_it.first)); } } return ParseToken(TokKind::kRbrace, "expects '}' to end sub attributes"); } bool HloParserImpl::ParseAttributes( const absl::flat_hash_map<std::string, AttrConfig>& attrs, bool allow_attributes) { LocTy loc = lexer_.GetLoc(); absl::flat_hash_set<std::string> seen_attrs; if (allow_attributes) { while (EatIfPresent(TokKind::kComma)) { if (!ParseAttributeHelper(attrs, &seen_attrs)) { return false; } } } // Check that all required attrs were seen. for (const auto& attr_it : attrs) { if (attr_it.second.required && seen_attrs.find(attr_it.first) == seen_attrs.end()) { return Error(loc, StrFormat("attribute %s is expected but not seen", attr_it.first)); } } return true; } bool HloParserImpl::ParseAttributeHelper( const absl::flat_hash_map<std::string, AttrConfig>& attrs, absl::flat_hash_set<std::string>* seen_attrs) { LocTy loc = lexer_.GetLoc(); std::string name; if (!ParseAttributeName(&name)) { return Error(loc, "error parsing attributes"); } VLOG(3) << "Parsing attribute " << name; if (!seen_attrs->insert(name).second) { return Error(loc, StrFormat("attribute %s already exists", name)); } auto attr_it = attrs.find(name); if (attr_it == attrs.end()) { std::string allowed_attrs; if (attrs.empty()) { allowed_attrs = "No attributes are allowed here."; } else { allowed_attrs = StrCat("Allowed attributes: ", StrJoin(attrs, ", ", [&](std::string* out, const std::pair<std::string, AttrConfig>& kv) { StrAppend(out, kv.first); })); } return Error( loc, StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } AttrTy attr_type = attr_it->second.attr_type; void* attr_out_ptr = attr_it->second.result; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); if (!success) { return Error(loc, StrFormat("error parsing attribute %s", name)); } return true; } VLOG(3) << "Parsing attribute " << name; bool success = [&] { LocTy attr_loc = lexer_.GetLoc(); switch (attr_type) { case AttrTy::kBool: { bool result; if (!ParseBool(&result)) { return false; } static_cast<optional<bool>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedBoolListOrBool: { if (!ParseBooleanListOrSingleBoolean( static_cast<BoolList*>(attr_out_ptr))) { return false; } return true; } case AttrTy::kInt64: { int64_t result; if (!ParseInt64(&result)) { return false; } static_cast<optional<int64_t>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kInt32: { int64_t result; if (!ParseInt64(&result)) { return false; } if (result != static_cast<int32_t>(result)) { return Error(attr_loc, "value out of range for int32_t"); } static_cast<optional<int32_t>*>(attr_out_ptr) ->emplace(static_cast<int32_t>(result)); return true; } case AttrTy::kFloat: { double result; if (!ParseDouble(&result)) { return false; } if (result > std::numeric_limits<float>::max() || result < std::numeric_limits<float>::lowest()) { return Error(attr_loc, "value out of range for float"); } static_cast<optional<float>*>(attr_out_ptr) ->emplace(static_cast<float>(result)); return true; } case AttrTy::kHloComputation: { HloComputation* result = nullptr; if (!ParseHloComputation(&result)) { return false; } static_cast<optional<HloComputation*>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kBracedHloComputationList: { std::vector<HloComputation*> result; if (!ParseHloComputationList(&result)) { return false; } static_cast<optional<std::vector<HloComputation*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFftType: { FftType result; if (!ParseFftType(&result)) { return false; } static_cast<optional<FftType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingType: { PaddingType result; if (!ParsePaddingType(&result)) { return false; } static_cast<optional<PaddingType>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kComparisonDirection: { ComparisonDirection result; if (!ParseComparisonDirection(&result)) { return false; } static_cast<optional<ComparisonDirection>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kComparisonType: { Comparison::Type result; if (!ParseComparisonType(&result)) { return false; } static_cast<optional<Comparison::Type>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kEnum: { if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects an enumeration value"); } std::string result = lexer_.GetStrVal(); lexer_.Lex(); static_cast<optional<std::string>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kWindow: { Window result; if (!ParseWindow(&result, /*expect_outer_curlies=*/true)) { return false; } static_cast<optional<Window>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kConvolutionDimensionNumbers: { ConvolutionDimensionNumbers result; if (!ParseConvolutionDimensionNumbers(&result)) { return false; } static_cast<optional<ConvolutionDimensionNumbers>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSharding: { OpSharding sharding; if (!ParseSharding(&sharding)) { return false; } static_cast<optional<OpSharding>*>(attr_out_ptr)->emplace(sharding); return true; } case AttrTy::kFrontendAttributes: { FrontendAttributes frontend_attributes; if (!ParseFrontendAttributes(&frontend_attributes)) { return false; } static_cast<optional<FrontendAttributes>*>(attr_out_ptr) ->emplace(frontend_attributes); return true; } case AttrTy::kStatisticsViz: { StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return false; } static_cast<optional<StatisticsViz>*>(attr_out_ptr) ->emplace(statistics_viz); return true; } case AttrTy::kParameterReplication: { ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return false; } static_cast<optional<ParameterReplication>*>(attr_out_ptr) ->emplace(parameter_replication); return true; } case AttrTy::kInstructionList: { std::vector<HloInstruction*> result; if (!ParseInstructionNames(&result)) { return false; } static_cast<optional<std::vector<HloInstruction*>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kFusionKind: { HloInstruction::FusionKind result; if (!ParseFusionKind(&result)) { return false; } static_cast<optional<HloInstruction::FusionKind>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64List: { std::vector<int64_t> result; if (!ParseInt64List(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<int64_t>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kBracedInt64ListList: { std::vector<std::vector<int64_t>> result; if (!ParseInt64ListList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, &result)) { return false; } static_cast<optional<std::vector<std::vector<int64_t>>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSliceRanges: { SliceRanges result; if (!ParseSliceRanges(&result)) { return false; } static_cast<optional<SliceRanges>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPaddingConfig: { PaddingConfig result; if (!ParsePaddingConfig(&result)) { return false; } static_cast<optional<PaddingConfig>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kString: { std::string result; if (!ParseString(&result)) { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kStringOrJsonDict: { std::string result; if (lexer_.GetKind() == TokKind::kString) { if (!ParseString(&result)) { return false; } } else if (lexer_.GetKind() == TokKind::kLbrace) { if (!ParseJsonDict(&result)) { return false; } } else { return false; } static_cast<optional<std::string>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kMetadata: { OpMetadata result; if (!ParseMetadata(&result)) { return false; } static_cast<optional<OpMetadata>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kDistribution: { RandomDistribution result; if (!ParseRandomDistribution(&result)) { return false; } static_cast<optional<RandomDistribution>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kDomain: { return ParseDomain(static_cast<DomainData*>(attr_out_ptr)); } case AttrTy::kPrecisionList: { std::vector<PrecisionConfig::Precision> result; if (!ParsePrecisionList(&result)) { return false; } static_cast<optional<std::vector<PrecisionConfig::Precision>>*>( attr_out_ptr) ->emplace(result); return true; } case AttrTy::kShape: { Shape result; if (!ParseShape(&result)) { return false; } static_cast<optional<Shape>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kShapeList: { std::vector<Shape> result; if (!ParseShapeList(&result)) { return false; } static_cast<optional<std::vector<Shape>>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kRandomAlgorithm: { RandomAlgorithm result; if (!ParseRandomAlgorithm(&result)) { return false; } static_cast<optional<RandomAlgorithm>*>(attr_out_ptr)->emplace(result); return true; } case AttrTy::kPrecisionAlgorithm: { PrecisionConfig::Algorithm result; if (!ParseAlgorithm(&result)) { return false; } static_cast<optional<PrecisionConfig::Algorithm>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kAliasing: { AliasingData aliasing_data; if (!ParseAliasing(&aliasing_data)) { return false; } static_cast<optional<AliasingData>*>(attr_out_ptr) ->emplace(aliasing_data); return true; } case AttrTy::kBufferDonor: { BufferDonor buffer_donor; if (!ParseBufferDonor(&buffer_donor)) { return false; } static_cast<optional<BufferDonor>*>(attr_out_ptr) ->emplace(buffer_donor); return true; } case AttrTy::kComputationLayout: { ComputationLayout computation_layout(ShapeLayout(Shape{})); if (!ParseComputationLayout(&computation_layout)) { return false; } static_cast<optional<ComputationLayout>*>(attr_out_ptr) ->emplace(computation_layout); return true; } case AttrTy::kInstructionAliasing: { std::vector<std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>> aliasing_output_operand_pairs; if (!ParseInstructionOutputOperandAliasing( &aliasing_output_operand_pairs)) { return false; } static_cast<optional<std::vector< std::pair<ShapeIndex, std::pair<int64_t, ShapeIndex>>>>*>( attr_out_ptr) ->emplace(std::move(aliasing_output_operand_pairs)); return true; } case AttrTy::kLiteral: { Literal result; if (!ParseLiteral(&result)) { return false; } static_cast<optional<Literal>*>(attr_out_ptr) ->emplace(std::move(result)); return true; } case AttrTy::kCustomCallSchedule: { CustomCallSchedule result; if (!ParseCustomCallSchedule(&result)) { return false; } static_cast<optional<CustomCallSchedule>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kCustomCallApiVersion: { CustomCallApiVersion result; if (!ParseCustomCallApiVersion(&result)) { return false; } static_cast<optional<CustomCallApiVersion>*>(attr_out_ptr) ->emplace(result); return true; } case AttrTy::kSparsityDescriptor: { std::vector<SparsityDescriptor> result; if (!ParseSparsityDescriptor(&result)) { return false; } *static_cast<std::vector<SparsityDescriptor>*>(attr_out_ptr) = std::move(result); return true; } } }(); bool HloParserImpl::CopyAttributeToProtoMessage( absl::flat_hash_set<std::string> non_proto_attrs, const absl::flat_hash_map<std::string, AttrConfig>& attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); const tsl::protobuf::Reflection* reflection = message->GetReflection(); for (const auto& p : attrs) { const std::string& name = p.first; if (non_proto_attrs.find(name) != non_proto_attrs.end()) { continue; } const tsl::protobuf::FieldDescriptor* fd = descriptor->FindFieldByName(name); if (!fd) { std::string allowed_attrs = "Allowed attributes: "; for (int i = 0; i < descriptor->field_count(); ++i) { if (i == 0) { absl::StrAppend(&allowed_attrs, descriptor->field(i)->name()); } else { absl::StrAppend(&allowed_attrs, ", ", descriptor->field(i)->name()); } } return TokenError( StrFormat("unexpected attribute \"%s\". %s", name, allowed_attrs)); } CHECK(!fd->is_repeated()); // Repeated fields not implemented. bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); if (!success) { return TokenError(StrFormat("error parsing attribute %s", name)); } } return true; } bool success = [&] { switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { auto attr_value = static_cast<optional<bool>*>(p.second.result); if (attr_value->has_value()) { reflection->SetBool(message, fd, **attr_value); } return true; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { auto attr_value = static_cast<optional<std::string>*>(p.second.result); if (attr_value->has_value()) { const tsl::protobuf::EnumValueDescriptor* evd = fd->enum_type()->FindValueByName(**attr_value); reflection->SetEnum(message, fd, evd); } return true; } default: return false; } }(); bool HloParserImpl::ParseAttributesAsProtoMessage( const absl::flat_hash_map<std::string, AttrConfig>& non_proto_attrs, tsl::protobuf::Message* message) { const tsl::protobuf::Descriptor* descriptor = message->GetDescriptor(); absl::flat_hash_map<std::string, AttrConfig> attrs; // Storage for attributes. std::vector<optional<bool>> bool_params; std::vector<optional<std::string>> string_params; // Reserve enough capacity to make sure that the vector is not growing, so we // can rely on the pointers to stay valid. bool_params.reserve(descriptor->field_count()); string_params.reserve(descriptor->field_count()); // Populate the storage of expected attributes from the protobuf description. for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) { const tsl::protobuf::FieldDescriptor* fd = descriptor->field(field_idx); const std::string& field_name = fd->name(); switch (fd->type()) { case tsl::protobuf::FieldDescriptor::TYPE_BOOL: { bool_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kBool, &bool_params.back()}; break; } case tsl::protobuf::FieldDescriptor::TYPE_ENUM: { string_params.emplace_back(std::nullopt); attrs[field_name] = {/*is_required*/ false, AttrTy::kEnum, &string_params.back()}; break; } default: return TokenError(absl::StrFormat( "Unexpected protocol buffer type: %s ", fd->DebugString())); } } absl::flat_hash_set<std::string> non_proto_attrs_names; non_proto_attrs_names.reserve(non_proto_attrs.size()); for (const auto& p : non_proto_attrs) { const std::string& attr_name = p.first; // If an attribute is both specified within 'non_proto_attrs' and an // attribute of the proto message, we prefer the attribute of the proto // message. if (attrs.find(attr_name) == attrs.end()) { non_proto_attrs_names.insert(attr_name); attrs[attr_name] = p.second; } } if (!ParseAttributes(attrs)) { return false; } return CopyAttributeToProtoMessage(non_proto_attrs_names, attrs, message); } bool HloParserImpl::ParseComputationName(HloComputation** value) { std::string name; LocTy loc = lexer_.GetLoc(); if (!ParseName(&name)) { return Error(loc, "expects computation name"); } std::pair<HloComputation*, LocTy>* computation = tsl::gtl::FindOrNull(computation_pool_, name); if (computation == nullptr) { return Error(loc, StrCat("computation does not exist: ", name)); } *value = computation->first; return true; } bool HloParserImpl::ParseWindow(Window* window, bool expect_outer_curlies) { LocTy loc = lexer_.GetLoc(); if (expect_outer_curlies && !ParseToken(TokKind::kLbrace, "expected '{' to start window attribute")) { return false; } std::vector<int64_t> size; std::vector<int64_t> stride; std::vector<std::vector<int64_t>> pad; std::vector<int64_t> lhs_dilate; std::vector<int64_t> rhs_dilate; std::vector<int64_t> rhs_reversal; const auto end_token = expect_outer_curlies ? TokKind::kRbrace : TokKind::kEof; while (lexer_.GetKind() != end_token) { LocTy attr_loc = lexer_.GetLoc(); std::string field_name; if (!ParseAttributeName(&field_name)) { return Error(attr_loc, "expects sub-attributes in window"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); if (!ok) { return false; } } if (!stride.empty() && stride.size() != size.size()) { return Error(loc, "expects 'stride=' has the same size as 'size='"); } if (!lhs_dilate.empty() && lhs_dilate.size() != size.size()) { return Error(loc, "expects 'lhs_dilate=' has the same size as 'size='"); } if (!rhs_dilate.empty() && rhs_dilate.size() != size.size()) { return Error(loc, "expects 'rhs_dilate=' has the same size as 'size='"); } if (!pad.empty() && pad.size() != size.size()) { return Error(loc, "expects 'pad=' has the same size as 'size='"); } for (int i = 0; i < size.size(); i++) { window->add_dimensions()->set_size(size[i]); if (!pad.empty()) { window->mutable_dimensions(i)->set_padding_low(pad[i][0]); window->mutable_dimensions(i)->set_padding_high(pad[i][1]); } // If some field is not present, it has the default value. window->mutable_dimensions(i)->set_stride(stride.empty() ? 1 : stride[i]); window->mutable_dimensions(i)->set_base_dilation( lhs_dilate.empty() ? 1 : lhs_dilate[i]); window->mutable_dimensions(i)->set_window_dilation( rhs_dilate.empty() ? 1 : rhs_dilate[i]); window->mutable_dimensions(i)->set_window_reversal( rhs_reversal.empty() ? false : (rhs_reversal[i] == 1)); } return !expect_outer_curlies || ParseToken(TokKind::kRbrace, "expected '}' to end window attribute"); } bool ok = [&] { if (field_name == "size") { return ParseDxD("size", &size); } if (field_name == "stride") { return ParseDxD("stride", &stride); } if (field_name == "lhs_dilate") { return ParseDxD("lhs_dilate", &lhs_dilate); } if (field_name == "rhs_dilate") { return ParseDxD("rls_dilate", &rhs_dilate); } if (field_name == "pad") { return ParseWindowPad(&pad); } if (field_name == "rhs_reversal") { return ParseDxD("rhs_reversal", &rhs_reversal); } return Error(attr_loc, StrCat("unexpected attribute name: ", field_name)); }(); bool HloParserImpl::ParseConvolutionDimensionNumbers( ConvolutionDimensionNumbers* dnums) { if (lexer_.GetKind() != TokKind::kDimLabels) { return TokenError("expects dim labels pattern, e.g., 'bf0_0io->0bf'"); } std::string str = lexer_.GetStrVal(); // The str is expected to have 3 items, lhs, rhs, out, and it must look like // lhs_rhs->out, that is, the first separator is "_" and the second is "->". std::vector<std::string> split1 = absl::StrSplit(str, '_'); if (split1.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } std::vector<std::string> split2 = absl::StrSplit(split1[1], "->"); if (split2.size() != 2) { LOG(FATAL) << "expects 3 items: lhs, rhs, and output dims, but sees " << str; } absl::string_view lhs = split1[0]; absl::string_view rhs = split2[0]; absl::string_view out = split2[1]; auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; // lhs { if (!is_unique(lhs)) { return TokenError( StrCat("expects unique lhs dimension numbers, but sees ", lhs)); } // Count number of spatial dimensions. for (char c : lhs) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_input_spatial_dimensions(-1); } } for (int i = 0; i < lhs.size(); i++) { char c = lhs[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_input_batch_dimension(i); } else if (c == 'f') { dnums->set_input_feature_dimension(i); } else if (c < '0' + lhs.size() && c >= '0') { dnums->set_input_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in lhs dimension numbers", lhs.size() - 1)); } } } // rhs { if (!is_unique(rhs)) { return TokenError( StrCat("expects unique rhs dimension numbers, but sees ", rhs)); } // Count number of spatial dimensions. for (char c : rhs) { if (c != 'i' && c != 'o' && c != '?') { dnums->add_kernel_spatial_dimensions(-1); } } for (int i = 0; i < rhs.size(); i++) { char c = rhs[i]; if (c == '?') { continue; } else if (c == 'i') { dnums->set_kernel_input_feature_dimension(i); } else if (c == 'o') { dnums->set_kernel_output_feature_dimension(i); } else if (c < '0' + rhs.size() && c >= '0') { dnums->set_kernel_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dio?] in rhs dimension numbers", rhs.size() - 1)); } } } // output { if (!is_unique(out)) { return TokenError( StrCat("expects unique output dimension numbers, but sees ", out)); } // Count number of spatial dimensions. for (char c : out) { if (c != 'b' && c != 'f' && c != '?') { dnums->add_output_spatial_dimensions(-1); } } for (int i = 0; i < out.size(); i++) { char c = out[i]; if (c == '?') { continue; } else if (c == 'b') { dnums->set_output_batch_dimension(i); } else if (c == 'f') { dnums->set_output_feature_dimension(i); } else if (c < '0' + out.size() && c >= '0') { dnums->set_output_spatial_dimensions(c - '0', i); } else { return TokenError(StrFormat( "expects [0-%dbf?] in output dimension numbers", out.size() - 1)); } } } // lhs, rhs, and output should have the same number of spatial dimensions. if (dnums->input_spatial_dimensions_size() != dnums->output_spatial_dimensions_size() || dnums->input_spatial_dimensions_size() != dnums->kernel_spatial_dimensions_size()) { return TokenError( StrFormat("input, kernel, and output must have same number of spatial " "dimensions, but got %d, %d, %d, respectively.", dnums->input_spatial_dimensions_size(), dnums->kernel_spatial_dimensions_size(), dnums->output_spatial_dimensions_size())); } lexer_.Lex(); return true; } auto is_unique = [](absl::string_view str) -> bool { absl::flat_hash_set<char> chars; for (char c : str) { // '?' dims are skipped. if (c == '?') { continue; } if (!chars.insert(c).second) { return false; } } return true; }; bool HloParserImpl::ParseSliceRanges(SliceRanges* result) { if (!ParseToken(TokKind::kLbrace, "expects '{' to start ranges")) { return false; } std::vector<std::vector<int64_t>> ranges; if (lexer_.GetKind() == TokKind::kRbrace) { // empty return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } do { LocTy loc = lexer_.GetLoc(); ranges.emplace_back(); if (!ParseInt64List(TokKind::kLsquare, TokKind::kRsquare, TokKind::kColon, &ranges.back())) { return false; } const auto& range = ranges.back(); if (range.size() != 2 && range.size() != 3) { return Error(loc, StrFormat("expects [start:limit:step] or [start:limit], " "but sees %d elements.", range.size())); } } while (EatIfPresent(TokKind::kComma)); for (const auto& range : ranges) { result->starts.push_back(range[0]); result->limits.push_back(range[1]); result->strides.push_back(range.size() == 3 ? range[2] : 1); } return ParseToken(TokKind::kRbrace, "expects '}' to end ranges"); } bool HloParserImpl::ParsePrecisionList( std::vector<PrecisionConfig::Precision>* result) { auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { PrecisionConfig::Precision item; if (!ParsePrecision(&item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseHloComputation(HloComputation** result) { if (lexer_.GetKind() == TokKind::kLbrace) { // This means it is a nested computation. return ParseInstructionList(result, /*computation_name=*/"_"); } // This means it is a computation name. return ParseComputationName(result); } bool HloParserImpl::ParseHloComputationList( std::vector<HloComputation*>* result) { auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { HloComputation* computation; if (!ParseHloComputation(&computation)) { return false; } VLOG(3) << "parsed computation " << computation->name(); result->push_back(computation); return true; }; VLOG(3) << "parsed computation " << computation->name(); bool HloParserImpl::ParseShapeList(std::vector<Shape>* result) { auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; return ParseList(TokKind::kLbrace, TokKind::kRbrace, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { Shape shape; if (!ParseShape(&shape)) { return false; } result->push_back(std::move(shape)); return true; }; bool HloParserImpl::ParseInt64List(const TokKind start, const TokKind end, const TokKind delim, std::vector<int64_t>* result) { auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } result->push_back(i); return true; }; bool HloParserImpl::ParseInt64ListList( const TokKind start, const TokKind end, const TokKind delim, std::vector<std::vector<int64_t>>* result) { auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; return ParseList(start, end, delim, parse_and_add_item); } auto parse_and_add_item = [&]() { std::vector<int64_t> item; if (!ParseInt64List(start, end, delim, &item)) { return false; } result->push_back(item); return true; }; bool HloParserImpl::ParseList(const TokKind start, const TokKind end, const TokKind delim, absl::FunctionRef<bool()> parse_and_add_item) { if (!ParseToken(start, StrCat("expects a list starting with ", TokKindToString(start)))) { return false; } if (lexer_.GetKind() == end) { // empty } else { do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(delim)); } return ParseToken( end, StrCat("expects a list to end with ", TokKindToString(end))); } bool HloParserImpl::ParseParamListToShape(Shape* shape, LocTy* shape_loc) { if (!ParseParamList() || !ParseToken(TokKind::kArrow, "expects '->'")) { return false; } *shape_loc = lexer_.GetLoc(); return ParseShape(shape); } bool HloParserImpl::ParseParamList() { if (!ParseToken(TokKind::kLparen, "expects '(' at the beginning of param list")) { return false; } if (lexer_.GetKind() == TokKind::kRparen) { // empty } else { do { Shape shape; std::string name; if (!ParseName(&name) || !ParseShape(&shape)) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRparen, "expects ')' at the end of param list"); } bool HloParserImpl::ParseDimensionSizes(std::vector<int64_t>* dimension_sizes, std::vector<bool>* dynamic_dimensions) { auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; return ParseList(TokKind::kLsquare, TokKind::kRsquare, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { int64_t i; bool is_dynamic = false; if (lexer_.GetKind() == TokKind::kQuestionMark) { i = Shape::kUnboundedSize; is_dynamic = true; lexer_.Lex(); } else { if (lexer_.GetKind() == TokKind::kLeq) { is_dynamic = true; lexer_.Lex(); } if (!ParseInt64(&i)) { return false; } } dimension_sizes->push_back(i); dynamic_dimensions->push_back(is_dynamic); return true; }; bool HloParserImpl::ParseDimLevelTypes( absl::InlinedVector<DimLevelType, InlineRank()>* dim_level_types, absl::InlinedVector<bool, InlineRank()>* dim_unique, absl::InlinedVector<bool, InlineRank()>* dim_ordered) { auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; return ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_item); } auto parse_and_add_item = [&]() { if (lexer_.GetKind() == TokKind::kIdent) { bool dim_level_type_valid = false; DimLevelType dim_level_type; if (lexer_.GetStrVal() == "D") { lexer_.Lex(); dim_level_type = DIM_DENSE; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "C") { lexer_.Lex(); dim_level_type = DIM_COMPRESSED; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "S") { lexer_.Lex(); dim_level_type = DIM_SINGLETON; dim_level_type_valid = true; } else if (lexer_.GetStrVal() == "H") { lexer_.Lex(); dim_level_type = DIM_LOOSE_COMPRESSED; dim_level_type_valid = true; } if (dim_level_type_valid) { bool new_dim_unique = true; if (lexer_.GetKind() == TokKind::kPlus) { new_dim_unique = false; lexer_.Lex(); } bool new_dim_ordered = true; if (lexer_.GetKind() == TokKind::kTilde) { new_dim_ordered = false; lexer_.Lex(); } if (!LayoutUtil::ValidateDimLevel(dim_level_type, new_dim_unique, new_dim_ordered)) { return Error( lexer_.GetLoc(), "invalid DimLevelType/unique/ordered combination in shape"); } dim_level_types->push_back(dim_level_type); dim_unique->push_back(new_dim_unique); dim_ordered->push_back(new_dim_ordered); return true; } } return Error(lexer_.GetLoc(), "expected a DimLevelType abbreviation (D, C, or S)"); }; bool HloParserImpl::ParseTiles(std::vector<Tile>* tiles) { auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; do { tiles->push_back(Tile()); if (!ParseList(TokKind::kLparen, TokKind::kRparen, TokKind::kComma, parse_and_add_tile_dimension)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_tile_dimension = [&]() { int64_t i; if (ParseInt64(&i)) { tiles->back().add_dimensions(i); return true; } if (lexer_.GetKind() == TokKind::kAsterisk) { tiles->back().add_dimensions(Tile::kCombineDimension); lexer_.Lex(); return true; } return false; }; bool HloParserImpl::ParsePhysicalShape(Shape* physical_shape) { if (!ParseToken(TokKind::kLparen, StrCat("expects physical shape to start with ", TokKindToString(TokKind::kLparen)))) { return false; } ParseShape(physical_shape); if (!ParseToken(TokKind::kRparen, StrCat("expects physical shape to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParsePrimitiveType(PrimitiveType* result) { if (lexer_.GetKind() != TokKind::kPrimitiveType) { return TokenError(absl::StrCat("expected primitive type, saw ", TokKindToString(lexer_.GetKind()))); } *result = lexer_.GetPrimitiveTypeVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseUnsignedIntegerType(PrimitiveType* primitive_type) { if (!ParsePrimitiveType(primitive_type)) { return false; } if (!primitive_util::IsUnsignedIntegralType(*primitive_type)) { return TokenError("expecting an unsigned integer type"); } return true; } bool HloParserImpl::ParseLayoutIntAttribute( int64_t* attr_value, absl::string_view attr_description) { if (!ParseToken(TokKind::kLparen, StrCat("expects ", attr_description, " to start with ", TokKindToString(TokKind::kLparen)))) { return false; } if (!ParseInt64(attr_value)) { return false; } if (!ParseToken(TokKind::kRparen, StrCat("expects ", attr_description, " to end with ", TokKindToString(TokKind::kRparen)))) { return false; } return true; } bool HloParserImpl::ParseSplitConfigs(std::vector<SplitConfig>& split_configs) { auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; do { if (!ParseToken(TokKind::kLparen, StrCat("expects split configs to start with ", TokKindToString(TokKind::kLparen)))) { return false; } int64_t dimension; if (!ParseInt64(&dimension)) { return false; } split_configs.push_back(SplitConfig(dimension, {})); if (!ParseList(TokKind::kColon, TokKind::kRparen, TokKind::kComma, parse_and_add_split_index)) { return false; } } while (lexer_.GetKind() == TokKind::kLparen); return true; } auto parse_and_add_split_index = [&]() { int64_t i; if (ParseInt64(&i)) { split_configs.back().add_split_indices(i); return true; } return false; }; bool HloParserImpl::ParseLayout(Layout* layout) { absl::InlinedVector<int64_t, InlineRank()> minor_to_major; DimLevelTypeVector dim_level_types; absl::InlinedVector<bool, InlineRank()> dim_unique; absl::InlinedVector<bool, InlineRank()> dim_ordered; std::vector<Tile> tiles; PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID; PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID; int64_t element_size_in_bits = 0; int64_t memory_space = 0; std::vector<SplitConfig> split_configs; std::optional<Shape> physical_shape; int64_t dynamic_shape_metadata_prefix_bytes = 0; int64_t tail_padding_alignment_in_elements = 1; auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; if (!ParseToken(TokKind::kLbrace, StrCat("expects layout to start with ", TokKindToString(TokKind::kLbrace)))) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { if (lexer_.GetKind() == TokKind::kInt) { // Parse minor to major. do { if (!parse_and_add_item()) { return false; } } while (EatIfPresent(TokKind::kComma)); } if (lexer_.GetKind() == TokKind::kColon) { lexer_.Lex(); if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "D") { lexer_.Lex(); ParseDimLevelTypes(&dim_level_types, &dim_unique, &dim_ordered); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "T") { lexer_.Lex(); ParseTiles(&tiles); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "L") { lexer_.Lex(); ParseLayoutIntAttribute(&tail_padding_alignment_in_elements, "multiple padded to in elements"); } if (lexer_.GetKind() == TokKind::kOctothorp) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kOctothorp), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&index_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects index primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kAsterisk) { lexer_.Lex(); ParseToken( TokKind::kLparen, StrCat("expects ", TokKindToString(TokKind::kAsterisk), " to be followed by ", TokKindToString(TokKind::kLparen))); ParseUnsignedIntegerType(&pointer_primitive_type); ParseToken(TokKind::kRparen, StrCat("expects pointer primitive type to be followed by ", TokKindToString(TokKind::kRparen))); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "E") { lexer_.Lex(); ParseLayoutIntAttribute(&element_size_in_bits, "element size in bits"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "S") { lexer_.Lex(); ParseLayoutIntAttribute(&memory_space, "memory space"); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "SC") { lexer_.Lex(); ParseSplitConfigs(split_configs); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "P") { lexer_.Lex(); physical_shape.emplace(); ParsePhysicalShape(&*physical_shape); } if (lexer_.GetKind() == TokKind::kIdent && lexer_.GetStrVal() == "M") { lexer_.Lex(); ParseLayoutIntAttribute(&dynamic_shape_metadata_prefix_bytes, "dynamic shape metadata prefix bytes"); } } } if (!ParseToken(TokKind::kRbrace, StrCat("expects layout to end with ", TokKindToString(TokKind::kRbrace)))) { return false; } std::vector<Tile> vec_tiles(tiles.size()); for (int i = 0; i < tiles.size(); i++) { vec_tiles[i] = Tile(tiles[i]); } *layout = LayoutUtil::MakeLayout( minor_to_major, dim_level_types, dim_unique, dim_ordered, vec_tiles, tail_padding_alignment_in_elements, index_primitive_type, pointer_primitive_type, element_size_in_bits, memory_space, split_configs, std::move(physical_shape), dynamic_shape_metadata_prefix_bytes); return true; } auto parse_and_add_item = [&]() { int64_t i; if (!ParseInt64(&i)) { return false; } minor_to_major.push_back(i); return true; }; bool HloParserImpl::ParseShape(Shape* result) { if (EatIfPresent(TokKind::kLparen)) { // Tuple std::vector<Shape> shapes; if (lexer_.GetKind() == TokKind::kRparen) { /*empty*/ } else { // shape (',' shape)* do { shapes.emplace_back(); if (!ParseShape(&shapes.back())) { return false; } } while (EatIfPresent(TokKind::kComma)); } *result = ShapeUtil::MakeTupleShape(shapes); return ParseToken(TokKind::kRparen, "expects ')' at the end of tuple."); } PrimitiveType primitive_type; if (!ParsePrimitiveType(&primitive_type)) { return false; } // Each element contains a dimension size and a bool indicating whether this // is a dynamic dimension. std::vector<int64_t> dimension_sizes; std::vector<bool> dynamic_dimensions; if (!ParseDimensionSizes(&dimension_sizes, &dynamic_dimensions)) { return false; } result->set_element_type(primitive_type); for (int i = 0; i < dimension_sizes.size(); ++i) { result->add_dimensions(dimension_sizes[i]); result->set_dynamic_dimension(i, dynamic_dimensions[i]); } LayoutUtil::SetToDefaultLayout(result); // We need to lookahead to see if a following open brace is the start of a // layout. The specific problematic case is: // // ENTRY %foo (x: f32[42]) -> f32[123] { // ... // } // // The open brace could either be the start of a computation or the start of a // layout for the f32[123] shape. We consider it the start of a layout if the // next token after the open brace is an integer or a colon. if (lexer_.GetKind() == TokKind::kLbrace && (lexer_.LookAhead() == TokKind::kInt || lexer_.LookAhead() == TokKind::kColon)) { Layout layout; if (!ParseLayout(&layout)) { return false; } if (layout.dim_level_types_size() != 0 && layout.dim_level_types_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but dim level types size is %ld.", result->rank(), layout.dim_level_types_size())); } if (layout.minor_to_major_size() != result->rank()) { return Error( lexer_.GetLoc(), StrFormat("Dimensions size is %ld, but minor to major size is %ld.", result->rank(), layout.minor_to_major_size())); } if (LayoutUtil::IsSparse(layout) && layout.tiles_size() > 0) { return Error(lexer_.GetLoc(), StrFormat("Layout has tiles, but is for a sparse array: %s", layout.ToString())); } if (!LayoutUtil::IsSparse(layout) && layout.has_physical_shape()) { return Error( lexer_.GetLoc(), StrFormat( "Layout has physical shape, but is not for a sparse array: %s", layout.ToString())); } *result->mutable_layout() = layout; } return true; } bool HloParserImpl::ParseName(std::string* result) { VLOG(3) << "ParseName"; if (lexer_.GetKind() != TokKind::kIdent && lexer_.GetKind() != TokKind::kName) { return TokenError("expects name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseName"; bool HloParserImpl::ParseAttributeName(std::string* result) { if (lexer_.GetKind() != TokKind::kAttributeName) { return TokenError("expects attribute name"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } bool HloParserImpl::ParseString(std::string* result) { VLOG(3) << "ParseString"; if (lexer_.GetKind() != TokKind::kString) { return TokenError("expects string"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseString"; bool HloParserImpl::ParseJsonDict(std::string* result) { VLOG(3) << "ParseJsonDict"; if (lexer_.LexJsonDict() != TokKind::kString) { return TokenError("expects JSON dict"); } *result = lexer_.GetStrVal(); lexer_.Lex(); return true; } VLOG(3) << "ParseJsonDict"; bool HloParserImpl::ParseDxD(const std::string& name, std::vector<int64_t>* result) { LocTy loc = lexer_.GetLoc(); if (!result->empty()) { return Error(loc, StrFormat("sub-attribute '%s=' already exists", name)); } // 1D if (lexer_.GetKind() == TokKind::kInt) { int64_t number; if (!ParseInt64(&number)) { return Error(loc, StrFormat("expects sub-attribute '%s=i'", name)); } result->push_back(number); return true; } // 2D or higher. if (lexer_.GetKind() == TokKind::kDxD) { std::string str = lexer_.GetStrVal(); if (!SplitToInt64s(str, 'x', result)) { return Error(loc, StrFormat("expects sub-attribute '%s=ixj...'", name)); } lexer_.Lex(); return true; } return TokenError("expects token type kInt or kDxD"); } bool HloParserImpl::ParseWindowPad(std::vector<std::vector<int64_t>>* pad) { LocTy loc = lexer_.GetLoc(); if (!pad->empty()) { return Error(loc, "sub-attribute 'pad=' already exists"); } if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects window pad pattern, e.g., '0_0x3_3'"); } std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> low_high; if (!SplitToInt64s(padding_dim_str, '_', &low_high) || low_high.size() != 2) { return Error(loc, "expects padding_low and padding_high separated by '_'"); } pad->push_back(low_high); } lexer_.Lex(); return true; } bool HloParserImpl::ParsePaddingConfig(PaddingConfig* padding) { if (lexer_.GetKind() != TokKind::kPad) { return TokenError("expects padding config, e.g., '0_0_0x3_3_1'"); } LocTy loc = lexer_.GetLoc(); std::string str = lexer_.GetStrVal(); for (const auto& padding_dim_str : absl::StrSplit(str, 'x')) { std::vector<int64_t> padding_dim; if (!SplitToInt64s(padding_dim_str, '_', &padding_dim) || (padding_dim.size() != 2 && padding_dim.size() != 3)) { return Error(loc, "expects padding config pattern like 'low_high_interior' or " "'low_high'"); } auto* dim = padding->add_dimensions(); dim->set_edge_padding_low(padding_dim[0]); dim->set_edge_padding_high(padding_dim[1]); dim->set_interior_padding(padding_dim.size() == 3 ? padding_dim[2] : 0); } lexer_.Lex(); return true; } bool HloParserImpl::ParseMetadata(OpMetadata* metadata) { absl::flat_hash_map<std::string, AttrConfig> attrs; optional<std::string> op_type; optional<std::string> op_name; optional<std::string> source_file; optional<int32_t> source_line; optional<std::vector<int64_t>> profile_type; optional<std::string> deduplicated_name; optional<bool> preserve_layout; attrs["op_type"] = {/*required=*/false, AttrTy::kString, &op_type}; attrs["op_name"] = {/*required=*/false, AttrTy::kString, &op_name}; attrs["source_file"] = {/*required=*/false, AttrTy::kString, &source_file}; attrs["source_line"] = {/*required=*/false, AttrTy::kInt32, &source_line}; attrs["profile_type"] = {/*required=*/false, AttrTy::kBracedInt64List, &profile_type}; attrs["deduplicated_name"] = {/*required=*/false, AttrTy::kString, &deduplicated_name}; attrs["preserve_layout"] = {/*required=*/false, AttrTy::kBool, &preserve_layout}; if (!ParseSubAttributes(attrs)) { return false; } if (op_type) { metadata->set_op_type(*op_type); } if (op_name) { metadata->set_op_name(*op_name); } if (source_file) { metadata->set_source_file(*source_file); } if (source_line) { metadata->set_source_line(*source_line); } if (profile_type) { for (const auto& type : *profile_type) { if (!ProfileType_IsValid(type)) { return false; } metadata->add_profile_type(static_cast<ProfileType>(type)); } } if (deduplicated_name) { metadata->set_deduplicated_name(*deduplicated_name); } if (preserve_layout) { metadata->set_preserve_layout(*preserve_layout); } else { metadata->set_preserve_layout(false); } return true; } bool HloParserImpl::ParseSingleOrListMetadata( tsl::protobuf::RepeatedPtrField<OpMetadata>* metadata) { if (lexer_.GetKind() == TokKind::kLbrace && lexer_.LookAhead() == TokKind::kLbrace) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start metadata list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { if (!ParseMetadata(metadata->Add())) { return false; } } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end metadata list"); } return ParseMetadata(metadata->Add()); } bool HloParserImpl::ParseOpShardingType(OpSharding::Type* type) { switch (lexer_.GetKind()) { case TokKind::kw_maximal: *type = OpSharding::MAXIMAL; lexer_.Lex(); break; case TokKind::kw_replicated: *type = OpSharding::REPLICATED; lexer_.Lex(); break; case TokKind::kw_manual: *type = OpSharding::MANUAL; lexer_.Lex(); break; default: return false; } return true; } bool HloParserImpl::ParseListShardingType( std::vector<OpSharding::Type>* types) { if (!ParseToken(TokKind::kLbrace, "expected '{' to start sharding type list")) { return false; } if (lexer_.GetKind() != TokKind::kRbrace) { do { OpSharding::Type type; if (!ParseOpShardingType(&type)) { return false; } types->emplace_back(type); } while (EatIfPresent(TokKind::kComma)); } return ParseToken(TokKind::kRbrace, "expected '}' to end sharding type list"); } bool HloParserImpl::ParseOpcode( HloOpcode* opcode, std::optional<HloOpcode>* async_wrapped_opcode) { VLOG(3) << "ParseOpcode"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects opcode"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToHloOpcode(val); if (!status_or_result.ok()) { auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; if (try_parsing_async_op("-start", HloOpcode::kAsyncStart) || try_parsing_async_op("-update", HloOpcode::kAsyncUpdate) || try_parsing_async_op("-done", HloOpcode::kAsyncDone)) { if (!status_or_result.ok()) { return TokenError( StrFormat("expects async wrapped opcode but sees: %s, error: %s", val, status_or_result.status().message())); } *async_wrapped_opcode = status_or_result.value(); } else { return TokenError(StrFormat("expects opcode but sees: %s, error: %s", val, status_or_result.status().message())); } } else { *opcode = status_or_result.value(); } lexer_.Lex(); return true; } VLOG(3) << "ParseOpcode"; auto try_parsing_async_op = [&](absl::string_view suffix, HloOpcode async_opcode) { absl::string_view wrapped_opcode_view(val); if (absl::ConsumeSuffix(&wrapped_opcode_view, suffix)) { *opcode = async_opcode; std::string wrapped_opcode(wrapped_opcode_view); status_or_result = StringToHloOpcode(wrapped_opcode); return true; } return false; }; bool HloParserImpl::ParseFftType(FftType* result) { VLOG(3) << "ParseFftType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fft type"); } std::string val = lexer_.GetStrVal(); if (!FftType_Parse(val, result) || !FftType_IsValid(*result)) { return TokenError(StrFormat("expects fft type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParseFftType"; bool HloParserImpl::ParsePaddingType(PaddingType* result) { VLOG(3) << "ParsePaddingType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects padding type"); } std::string val = lexer_.GetStrVal(); if (!PaddingType_Parse(val, result) || !PaddingType_IsValid(*result)) { return TokenError(StrFormat("expects padding type but sees: %s", val)); } lexer_.Lex(); return true; } VLOG(3) << "ParsePaddingType"; bool HloParserImpl::ParseComparisonDirection(ComparisonDirection* result) { VLOG(3) << "ParseComparisonDirection"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison direction"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonDirection(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects comparison direction but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseComparisonDirection"; bool HloParserImpl::ParseComparisonType(Comparison::Type* result) { VLOG(1) << "ParseComparisonType"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects comparison type"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToComparisonType(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects comparison type but sees: %s", val)); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(1) << "ParseComparisonType"; bool HloParserImpl::ParseFusionKind(HloInstruction::FusionKind* result) { VLOG(3) << "ParseFusionKind"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects fusion kind"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToFusionKind(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects fusion kind but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseFusionKind"; bool HloParserImpl::ParseRandomDistribution(RandomDistribution* result) { VLOG(3) << "ParseRandomDistribution"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomDistribution(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random distribution but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomDistribution"; bool HloParserImpl::ParseRandomAlgorithm(RandomAlgorithm* result) { VLOG(3) << "ParseRandomAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToRandomAlgorithm(val); if (!status_or_result.ok()) { return TokenError( StrFormat("expects random algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseRandomAlgorithm"; bool HloParserImpl::ParsePrecision(PrecisionConfig::Precision* result) { VLOG(3) << "ParsePrecision"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects random distribution"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToPrecision(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects precision but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParsePrecision"; bool HloParserImpl::ParseAlgorithm(PrecisionConfig::Algorithm* result) { VLOG(3) << "ParseAlgorithm"; if (lexer_.GetKind() != TokKind::kIdent) { return TokenError("expects algorithm"); } std::string val = lexer_.GetStrVal(); auto status_or_result = StringToAlgorithm(val); if (!status_or_result.ok()) { return TokenError(StrFormat("expects algorithm but sees: %s, error: %s", val, status_or_result.status().message())); } *result = status_or_result.value(); lexer_.Lex(); return true; } VLOG(3) << "ParseAlgorithm"; bool HloParserImpl::ParseInt64(int64_t* result) { VLOG(3) << "ParseInt64"; if (lexer_.GetKind() != TokKind::kInt) { return TokenError("expects integer"); } *result = lexer_.GetInt64Val(); lexer_.Lex(); return true; } VLOG(3) << "ParseInt64"; bool HloParserImpl::ParseDouble(double* result) { switch (lexer_.GetKind()) { case TokKind::kDecimal: { double val = lexer_.GetDecimalVal(); // If GetDecimalVal returns +/-inf, that means that we overflowed // `double`. if (std::isinf(val)) { return TokenError(StrCat("Constant is out of range for double (+/-", std::numeric_limits<double>::max(), ") and so is unparsable.")); } *result = val; break; } case TokKind::kInt: *result = static_cast<double>(lexer_.GetInt64Val()); break; case TokKind::kw_inf: *result = std::numeric_limits<double>::infinity(); break; case TokKind::kNegInf: *result = -std::numeric_limits<double>::infinity(); break; default: return TokenError("expects decimal or integer"); } lexer_.Lex(); return true; } bool HloParserImpl::ParseComplex(std::complex<double>* result) { if (lexer_.GetKind() != TokKind::kLparen) { return TokenError("expects '(' before complex number"); } lexer_.Lex(); double real; LocTy loc = lexer_.GetLoc(); if (!ParseDouble(&real)) { return Error(loc, "expect floating-point value for real part of complex number"); } if (lexer_.GetKind() != TokKind::kComma) { return TokenError( absl::StrFormat("expect comma after real part of complex literal")); } lexer_.Lex(); double imag; loc = lexer_.GetLoc(); if (!ParseDouble(&imag)) { return Error( loc, "expect floating-point value for imaginary part of complex number"); } if (lexer_.GetKind() != TokKind::kRparen) { return TokenError(absl::StrFormat("expect ')' after complex number")); } *result = std::complex<double>(real, imag); lexer_.Lex(); return true; } bool HloParserImpl::ParseBool(bool* result) { if (lexer_.GetKind() != TokKind::kw_true && lexer_.GetKind() != TokKind::kw_false) { return TokenError("expects true or false"); } *result = lexer_.GetKind() == TokKind::kw_true; lexer_.Lex(); return true; } bool HloParserImpl::ParseToken(TokKind kind, const std::string& msg) { VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; if (lexer_.GetKind() != kind) { return TokenError(msg); } lexer_.Lex(); return true; } VLOG(3) << "ParseToken " << TokKindToString(kind) << " " << msg; bool HloParserImpl::AddInstruction(const std::string& name, HloInstruction* instruction, LocTy name_loc) { auto result = current_name_table().insert({name, {instruction, name_loc}}); if (!result.second) { Error(name_loc, StrCat("instruction already exists: ", name)); return Error(/*loc=*/result.first->second.second, "instruction previously defined here"); } return true; } bool HloParserImpl::AddComputation(const std::string& name, HloComputation* computation, LocTy name_loc) { auto result = computation_pool_.insert({name, {computation, name_loc}}); if (!result.second) { Error(name_loc, StrCat("computation already exists: ", name)); return Error(/*loc=*/result.first->second.second, "computation previously defined here"); } return true; } absl::StatusOr<Shape> HloParserImpl::ParseShapeOnly() { lexer_.Lex(); Shape shape; if (!ParseShape(&shape)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after shape"); } return shape; } absl::StatusOr<Layout> HloParserImpl::ParseLayoutOnly() { lexer_.Lex(); Layout layout; if (!ParseLayout(&layout)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after layout"); } return layout; } absl::StatusOr<HloSharding> HloParserImpl::ParseShardingOnly() { lexer_.Lex(); OpSharding op_sharding; if (!ParseSharding(&op_sharding)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after sharding"); } return HloSharding::FromProto(op_sharding); } HloParserImpl::ParseFrontendAttributesOnly() { lexer_.Lex(); FrontendAttributes attributes; if (!ParseFrontendAttributes(&attributes)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after frontend attributes"); } return attributes; } absl::StatusOr<StatisticsViz> HloParserImpl::ParseStatisticsVizOnly() { lexer_.Lex(); StatisticsViz statistics_viz; if (!ParseStatisticsViz(&statistics_viz)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after statistics"); } return statistics_viz; } HloParserImpl::ParseParameterReplicationOnly() { lexer_.Lex(); ParameterReplication parameter_replication; if (!ParseParameterReplication(&parameter_replication)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after parameter replication"); } return std::vector<bool>( parameter_replication.replicated_at_leaf_buffers().begin(), parameter_replication.replicated_at_leaf_buffers().end()); } HloParserImpl::ParseBooleanListOrSingleBooleanOnly() { lexer_.Lex(); BoolList booleans; if (!ParseBooleanListOrSingleBoolean(&booleans)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after boolean list"); } return booleans; } HloParserImpl::ParseReplicaGroupsOnly() { lexer_.Lex(); std::vector<ReplicaGroup> replica_groups; if (!ParseReplicaGroupsOnly(&replica_groups)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after replica groups"); } return replica_groups; } absl::StatusOr<Window> HloParserImpl::ParseWindowOnly() { lexer_.Lex(); Window window; if (!ParseWindow(&window, /*expect_outer_curlies=*/false)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after window"); } return window; } HloParserImpl::ParseConvolutionDimensionNumbersOnly() { lexer_.Lex(); ConvolutionDimensionNumbers dnums; if (!ParseConvolutionDimensionNumbers(&dnums)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument( "Syntax error:\nExtra content after convolution dnums"); } return dnums; } absl::StatusOr<PaddingConfig> HloParserImpl::ParsePaddingConfigOnly() { lexer_.Lex(); PaddingConfig padding_config; if (!ParsePaddingConfig(&padding_config)) { return InvalidArgument("Syntax error:\n%s", GetError()); } if (lexer_.GetKind() != TokKind::kEof) { return InvalidArgument("Syntax error:\nExtra content after PaddingConfig"); } return padding_config; } bool HloParserImpl::ParseSingleInstruction(HloModule* module) { if (create_missing_instruction_ != nullptr || !scoped_name_tables_.empty()) { LOG(FATAL) << "Parser state is not clean. Please do not call any other " "methods before calling ParseSingleInstruction."; } HloComputation::Builder builder(module->name()); // The missing instruction hook we register creates the shaped instruction on // the fly as a parameter and returns it. int64_t parameter_count = 0; create_missing_instruction_ = [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; // Parse the instruction with the registered hook. Scope scope(&scoped_name_tables_); if (CanBeShape()) { // This means that the instruction's left-hand side is probably omitted, // e.g. // // f32[10] fusion(...), calls={...} if (!ParseInstructionRhs(&builder, module->name(), lexer_.GetLoc())) { return false; } } else { // This means that the instruction's left-hand side might exist, e.g. // // foo = f32[10] fusion(...), calls={...} std::string root_name; if (!ParseInstruction(&builder, &root_name)) { return false; } } if (lexer_.GetKind() != TokKind::kEof) { Error( lexer_.GetLoc(), "Syntax error:\nExpected eof after parsing single instruction. Did you" " mean to write an HLO module and forget the \"HloModule\" header?"); return false; } module->AddEntryComputation(builder.Build()); for (auto& comp : computations_) { module->AddEmbeddedComputation(std::move(comp)); } TF_CHECK_OK(module->set_schedule(ScheduleFromInstructionOrder(module))); return true; } [this, &builder, &parameter_count]( const std::string& name, const Shape& shape) -> std::pair<HloInstruction*, LocTy>* { std::string new_name = name.empty() ? StrCat("_", parameter_count) : name; HloInstruction* parameter = builder.AddInstruction( HloInstruction::CreateParameter(parameter_count++, shape, new_name)); current_name_table()[new_name] = {parameter, lexer_.GetLoc()}; return tsl::gtl::FindOrNull(current_name_table(), new_name); }; absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str, const HloModuleConfig& config) { auto module = std::make_unique<HloModule>(/*name=*/"_", config); HloParserImpl parser(str); TF_RETURN_IF_ERROR(parser.Run(module.get())); return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> ParseAndReturnUnverifiedModule( absl::string_view str) { return ParseAndReturnUnverifiedModule(str, HloModuleConfig()); } absl::StatusOr<HloSharding> ParseSharding(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShardingOnly(); } absl::StatusOr<FrontendAttributes> ParseFrontendAttributes( absl::string_view str) { HloParserImpl parser(str); return parser.ParseFrontendAttributesOnly(); } absl::StatusOr<StatisticsViz> ParseStatisticsViz(absl::string_view str) { HloParserImpl parser(str); return parser.ParseStatisticsVizOnly(); } absl::StatusOr<std::vector<bool>> ParseParameterReplication( absl::string_view str) { HloParserImpl parser(str); return parser.ParseParameterReplicationOnly(); } absl::StatusOr<HloParserImpl::BoolList> ParseBooleanListOrSingleBoolean( absl::string_view str) { HloParserImpl parser(str); return parser.ParseBooleanListOrSingleBooleanOnly(); } absl::StatusOr<std::vector<ReplicaGroup>> ParseReplicaGroupsOnly( absl::string_view str) { HloParserImpl parser(str); return parser.ParseReplicaGroupsOnly(); } absl::StatusOr<Window> ParseWindow(absl::string_view str) { HloParserImpl parser(str); return parser.ParseWindowOnly(); } absl::StatusOr<ConvolutionDimensionNumbers> ParseConvolutionDimensionNumbers( absl::string_view str) { HloParserImpl parser(str); return parser.ParseConvolutionDimensionNumbersOnly(); } absl::StatusOr<PaddingConfig> ParsePaddingConfig(absl::string_view str) { HloParserImpl parser(str); return parser.ParsePaddingConfigOnly(); } absl::StatusOr<Shape> ParseShape(absl::string_view str) { HloParserImpl parser(str); return parser.ParseShapeOnly(); } absl::StatusOr<Layout> ParseLayout(absl::string_view str) { HloParserImpl parser(str); return parser.ParseLayoutOnly(); } std::unique_ptr<HloParser> HloParser::CreateHloParserForTests( absl::string_view str) { return std::make_unique<HloParserImpl>(str); }
#include "xla/service/hlo_parser.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include <gtest/gtest.h> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/hlo/ir/hlo_casting_utils.h" #include "xla/hlo/ir/hlo_frontend_attributes.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_instructions.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tests/verified_hlo_module.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class HloParserTest : public ::testing::Test { protected: static void ExpectHasSubstr(string_view s, string_view expected) { EXPECT_TRUE(absl::StrContains(s, expected)) << "'" << s << "' does not contain '" << expected << "'"; } absl::StatusOr<std::unique_ptr<VerifiedHloModule>> ParseAndReturnVerifiedModule(absl::string_view hlo_text) { auto module = std::make_unique<VerifiedHloModule>( ::testing::UnitTest::GetInstance()->current_test_info()->name(), HloModuleConfig(), /*verifier_layout_sensitive=*/false, /*allow_mixed_precision_in_hlo_verifier=*/true, ShapeUtil::ByteSizeOfElements); TF_RETURN_IF_ERROR(module->ParseHloStringAndVerifyModule(hlo_text)); return std::move(module); } }; TEST_F(HloParserTest, CheckAllowSpmdShardingPropagationToOutput) { const char* const hlo_string = R"( HloModule TestModule, allow_spmd_sharding_propagation_to_output=true ENTRY TestComputation { p0 = f16[2048,1024] parameter(0) p1 = f16[2048,1024] parameter(1) ROOT root = (f16[2048,1024], f16[2048,1024]) tuple(p0, p1) } )"; auto result = ParseAndReturnVerifiedModule(hlo_string); TF_EXPECT_OK(result.status()); EXPECT_EQ( (*result)->config().allow_spmd_sharding_propagation_to_output().size(), 1); EXPECT_TRUE( (*result)->config().allow_spmd_sharding_propagation_to_output()[0]); }